package com.ahau.againstpestinfo.HttpProcessor;

import android.content.Context;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.apache.http.HttpEntity;

import java.util.Map;


/**
 * 注释:
 *
 * @author fanchunchun
 * @date 2018/4/6
 */

public class AsyncProcessor implements IHttpProcessor {

    public static final String TAG = "AsyncProcessor";

    Context  mContext;
    @Override
    public void post(String url, Map<String, Object> params, final ICallback callback) {

        // 创建异步请求端对象
        AsyncHttpClient client = new AsyncHttpClient();

        // 发送get请求对象
        client.post(mContext,url, (HttpEntity) params,"application/json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String result = new String(bytes);
                callback.onSuccess(result);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                callback.onSuccess(throwable.toString());
            }
        });

    }

    @Override
    public void get(String url, Map<String, Object> params, final ICallback callback) {

        // 创建异步请求端对象
        AsyncHttpClient client = new AsyncHttpClient();

        // 发送get请求对象
        client.get(url, new AsyncHttpResponseHandler() {


            @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        String result = new String(bytes);
                        Log.i(TAG, "请求成功" + result);
                        callback.onSuccess(result);
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        Log.i(TAG, "请求异常" + throwable.toString());
                        callback.onSuccess(throwable.toString());
                    }
                }
        );
    }
}
