封装的HttpClient工具类

此工具类封装了HttpClient和handler以及接口回调,可以在主线程运行post和get方法,通过实现CallBack得到返回结果。

网络请求的工具类

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpUtil {
    private static final String CHARSET = "UTF-8";
    private final static int TIME_OUT = 1000 * 15;

    //must on ui thread
    public static void get(final String url, final LinkedHashMap<String,String> params, final Callback callback) {
        final Handler handler = new Handler();
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                String uri = urlBuild(url, params);
                Log.d("httpUtil--get",uri);

                HttpGet getMethod = new HttpGet(uri);
                HttpClient httpClient = new DefaultHttpClient();
                //请求超时
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
                //读取超时
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);

                try {
                    HttpResponse response = httpClient.execute(getMethod); //发起GET请求
                    int statusCode = response.getStatusLine().getStatusCode();
                    String result = EntityUtils.toString(response.getEntity(), CHARSET);
                    resultHandler(statusCode, result, callback, handler);
                } catch (Exception e) {
                    failureHandler(handler, callback, e);
                }
            }
        }).start();
    }

    //must on ui thread
    public static void post(final String url, final LinkedHashMap<String,String> params, final Callback callback) {
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    HttpClient client = new DefaultHttpClient();
                    //请求超时
                    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
                    //读取超时
                    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);

                    HttpPost postMethod = new HttpPost(url);

                    String parstring =new JSONObject( params).toString();
                    List<NameValuePair> datas = new ArrayList<NameValuePair>();
                    datas.add(new BasicNameValuePair("data", DesUtils.encode(parstring)));

                    postMethod.setEntity(new UrlEncodedFormEntity(datas, CHARSET)); //将参数填入POST Entity中

                    HttpResponse response = client.execute(postMethod); //执行POST方法
                    int statusCode = response.getStatusLine().getStatusCode();
                    String result = EntityUtils.toString(response.getEntity(), CHARSET);
                    resultHandler(statusCode, result, callback, handler);
                } catch (Exception e) {
                    failureHandler(handler, callback, e);
                }
            }
        }).start();

    }

    public static String urlBuild(String url,LinkedHashMap<String, String> parameter) {
        StringBuilder stringBuilder = new StringBuilder();
        if (parameter == null || parameter.size() ==0){
            return url;
        }
        for (String key : parameter.keySet()){
            if (stringBuilder.length() == 0){
                stringBuilder.append(url+"?"+key + "=" + parameter.get(key));
            }else {
                stringBuilder.append("&" + key + "=" + parameter.get(key));
            }
        }
        return stringBuilder.toString();
    }

    private static void failureHandler(Handler handler, final Callback callback, final Exception e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onFailure(e.getMessage());
            }
        });
    }

    private static void resultHandler(final int code, final String result, final Callback callback, Handler handler) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    if (code == HttpStatus.SC_OK) {
                        //success
                        callback.onSuccess(result);
                    } else {
                        callback.onFailure(result);
                    }
                }
            }
        });
    }

}

回调接口

public interface Callback {
    void onSuccess(String result);
    void onFailure(String result);
}

主线程中请求代码

//post请求和get的请求参数写法相同) 
LinkedHashMap<String, String> paramMap = new LinkedHashMap<String, String>();
paramMap.put("name", "momo");
paramMap.put("age", "18");

HttpUtil.post("http://192.168.0.252:8080/post.do", paramMap, new Callback() {
        @Override
        public void onSuccess(String result) {
            Log.d("result","成功");
        }

        @Override
        public void onFailure(String result) {
            Log.d("result","失败");
        }
    });

你可能感兴趣的:(httpclient,android)