Android http 请求——AsyncHttpClient集成【解决重定向问题、setEnableRedirects 方法异常、线程中调用异常问题】


  1. 引用android-async-http-1.4.6.jar;
  2. 添加HttpUtils.java类后即可直接使用;
  • 参考资料:
    官网——https://github.com/loopj/android-async-http
    AsyncHttpClient 中的重定向和 setEnableRedirects 方法异常解决——http://www.tuicool.com/articles/RN3ieei
    AsyncHttpClient保持session——http://blog.csdn.net/ewrfedf/article/details/21968511
  • 中文版使用文档
    http://www.cnblogs.com/angeldevil/p/3729808.html


    /**
     * @Title:  HttpUtils.java
     * @Description:  http请求工具类
     * @author:  lijinghuan
     * @data:  2015-3-18 下午1:17:48
     */
    package com.tnt.decoration.common.utils;


    import java.io.File;
    import java.io.UnsupportedEncodingException;


    import org.apache.http.Header;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.params.ClientPNames;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.DefaultRedirectHandler;
    import org.apache.http.protocol.HttpContext;


    import android.content.Context;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.Message;


    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.FileAsyncHttpResponseHandler;
    import com.loopj.android.http.PersistentCookieStore;
    import com.loopj.android.http.RequestParams;
    import com.tnt.decoration.common.enums.ConstEnum;
    import com.tnt.decoration.common.logger.Logger;


    public class HttpUtils {


    private static AsyncHttpClientOverride httpclient = null;
    private Object obj = null;
    private String REQ_KEY = "e74c9816a5b84a8eab5987d426f44b89";
    private final int POST_REQUEST_OBJECT = 1340885334;
    private final int POST_XML_REQUEST_OBJECT = 23261600;
    private final int GET_REQUEST_OBJECT = 1410754409;
    private final int DOWNLOAD_FILE_OBJECT = 740213559;


    protected void onCompleted(String target, String respones) {


    }


    protected void onCompleted(String target, String tagcontent, File cachefile) {


    }


    protected void onError(int statusCode, Header[] headers, String respones,
    Throwable error) {


    }


    protected void onError(int statusCode, Header[] headers, String respones,
    Throwable error, String reqkey) {


    }


    protected void onPgress(int bytesWritten, int totalSize) {


    }


    protected void onReqFinish() {


    }


    public Object getObj() {
    return obj;
    }


    public void setObj(Object obj) {
    this.obj = obj;
    }


    private void instance(Context context, boolean flag) {
    if (httpclient == null || flag) {
    httpclient = new AsyncHttpClientOverride(true, 80, 443);
    httpclient.setTimeout(30000);
    httpclient.setEnableRedirects(true, true, true);
    httpclient.getHttpClient().getParams()
    .setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    httpclient
    .getHttpClient()
    .getParams()
    .setParameter(ClientPNames.MAX_REDIRECTS, Integer.MAX_VALUE);
    PersistentCookieStore mpcs = new PersistentCookieStore(context);
    httpclient.setCookieStore(mpcs);
    }
    }


    private void postRequestObject(Object paramesobj) {
    try {
    final RequestParamesEntity rpe = (RequestParamesEntity) paramesobj;
    instance(rpe.getContext(), false);
    httpclient.getHttpClient().getParams()
    .setParameter(REQ_KEY, rpe.getReqKey());
    httpclient.post(rpe.getUrl(), rpe.getParams(),
    new AsyncHttpResponseHandler() {
    @Override
    public void onFailure(int statusCode, Header[] headers,
    byte[] responseBody, Throwable error) {
    if (statusCode == 0) {
    Logger.L.error(statusCode, error,
    JsonUtils.toStr(headers),
    JsonUtils.toStr(responseBody));
    } else if (statusCode == 401) {
    sendUnLoginBroadcast(rpe.getContext());
    }
    Object reqkeyobj = httpclient.getHttpClient()
    .getParams().getParameter(REQ_KEY);
    String respones = responseBody == null ? ""
    : new String(responseBody).toString();
    onError(statusCode, headers, respones, error);
    onError(statusCode,
    headers,
    respones,
    error,
    reqkeyobj == null ? "" : reqkeyobj
    .toString());
    }


    @Override
    public void onSuccess(int statusCode, Header[] headers,
    byte[] responseBody) {
    onCompleted(rpe.getTarget(),
    responseBody == null ? "" : new String(
    responseBody).toString());
    }


    @Override
    public void onFinish() {
    onReqFinish();
    }
    });
    } catch (Exception e) {
    Logger.L.error("post request object error:", e);
    }
    }


    public void didPostRequestObject(Context context, String target,
    String url, RequestParams params, String reqKey) {
    RequestParamesEntity rpe = new RequestParamesEntity();
    rpe.setContext(context);
    rpe.setTarget(target);
    rpe.setUrl(url);
    rpe.setParams(params);
    rpe.setReqKey(reqKey);
    mhandler.obtainMessage(POST_REQUEST_OBJECT, rpe).sendToTarget();
    }


    public void didPostRequestObject(Context context, String target,
    String url, RequestParams params) {
    didPostRequestObject(context, target, url, params, "");
    }


    public void didPostRequestObject(Context context, String target,
    String url, String reqKey) {
    didPostRequestObject(context, target, url, new RequestParams(), reqKey);
    }


    public void didPostRequestObject(Context context, String target, String url) {
    didPostRequestObject(context, target, url, new RequestParams(), "");
    }


    private void postXmlRequestObject(Object paramesobj) {
    try {
    final RequestParamesEntity rpe = (RequestParamesEntity) paramesobj;
    instance(rpe.getContext(), false);
    StringEntity entity = null;
    try {
    entity = new StringEntity(rpe.getPostContent(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
    Logger.L.error("build StringEntity object error:", e);
    }
    if (entity == null) {
    return;
    }
    httpclient.post(rpe.getContext(), rpe.getUrl(), entity,
    "string/xml;UTF-8", new AsyncHttpResponseHandler() {
    @Override
    public void onFailure(int statusCode, Header[] headers,
    byte[] responseBody, Throwable error) {
    if (statusCode == 0) {
    Logger.L.error(statusCode, error,
    JsonUtils.toStr(headers),
    JsonUtils.toStr(responseBody));
    } else if (statusCode == 401) {
    sendUnLoginBroadcast(rpe.getContext());
    }
    onError(statusCode, headers,
    responseBody == null ? "" : new String(
    responseBody).toString(), error);
    }


    @Override
    public void onSuccess(int statusCode, Header[] headers,
    byte[] responseBody) {
    onCompleted(rpe.getTarget(),
    responseBody == null ? "" : new String(
    responseBody).toString());
    }


    @Override
    public void onFinish() {
    onReqFinish();
    }
    });
    } catch (Exception e) {
    Logger.L.error("post xml request object error:", e);
    }
    }


    public void didPostXmlRequestObject(Context context, String target,
    String url, String postContent) {
    RequestParamesEntity rpe = new RequestParamesEntity();
    rpe.setContext(context);
    rpe.setTarget(target);
    rpe.setUrl(url);
    rpe.setPostContent(postContent);
    mhandler.obtainMessage(POST_XML_REQUEST_OBJECT, rpe).sendToTarget();
    }


    private void getRequestObject(Object paramesobj) {
    try {
    final RequestParamesEntity rpe = (RequestParamesEntity) paramesobj;
    instance(rpe.getContext(), false);
    httpclient.getHttpClient().getParams()
    .setParameter(REQ_KEY, rpe.getReqKey());
    httpclient.get(rpe.getUrl(), new AsyncHttpResponseHandler() {
    @Override
    public void onFailure(int statusCode, Header[] headers,
    byte[] responseBody, Throwable error) {
    if (statusCode == 0) {
    Logger.L.error(statusCode, error,
    JsonUtils.toStr(headers),
    JsonUtils.toStr(responseBody));
    } else if (statusCode == 401) {
    sendUnLoginBroadcast(rpe.getContext());
    }
    Object reqkeyobj = httpclient.getHttpClient().getParams()
    .getParameter(REQ_KEY);
    String respones = responseBody == null ? "" : new String(
    responseBody).toString();
    onError(statusCode, headers, respones, error);
    onError(statusCode, headers, respones, error,
    reqkeyobj == null ? "" : reqkeyobj.toString());
    }


    @Override
    public void onSuccess(int statusCode, Header[] headers,
    byte[] responseBody) {
    onCompleted(rpe.getTarget(), responseBody == null ? ""
    : new String(responseBody).toString());
    }


    @Override
    public void onProgress(int bytesWritten, int totalSize) {
    onPgress(bytesWritten, totalSize);
    }


    @Override
    public void onFinish() {
    onReqFinish();
    }
    });
    } catch (Exception e) {
    Logger.L.error("get request object error:", e);
    }
    }


    public void didGetRequestObject(Context context, String target, String url,
    RequestParams params, String reqKey) {
    RequestParamesEntity rpe = new RequestParamesEntity();
    rpe.setContext(context);
    rpe.setTarget(target);
    rpe.setUrl(url);
    rpe.setParams(params);
    rpe.setReqKey(reqKey);
    mhandler.obtainMessage(GET_REQUEST_OBJECT, rpe).sendToTarget();
    }


    public void didGetRequestObject(Context context, String target, String url,
    RequestParams params) {
    didGetRequestObject(context, target, url, params, "");
    }


    public void didGetRequestObject(Context context, String target, String url,
    String reqKey) {
    didGetRequestObject(context, target, url, new RequestParams(), reqKey);
    }


    public void didGetRequestObject(Context context, String target, String url) {
    didGetRequestObject(context, target, url, new RequestParams(), "");
    }


    private void didDownloadFileObject(Object paramesobj) {
    final RequestParamesEntity rpe = (RequestParamesEntity) paramesobj;
    instance(rpe.getContext(), false);
    httpclient.getHttpClient().getParams()
    .setParameter(REQ_KEY, rpe.getReqKey());
    httpclient.get(rpe.getUrl(),
    new FileAsyncHttpResponseHandler(rpe.getContext()) {
    @Override
    public void onSuccess(int statusCode, Header[] headers,
    File file) {
    onCompleted(rpe.getTarget(), rpe.getTagContent(), file);
    deleteTargetFile();
    }


    @Override
    public void onFailure(int statusCode, Header[] headers,
    Throwable error, File file) {
    if (statusCode == 0) {
    Logger.L.error(statusCode, error,
    JsonUtils.toStr(headers));
    } else if (statusCode == 401) {
    sendUnLoginBroadcast(rpe.getContext());
    }
    Object reqkeyobj = httpclient.getHttpClient()
    .getParams().getParameter(REQ_KEY);
    onError(statusCode, headers, "", error);
    onError(statusCode, headers, "", error,
    reqkeyobj == null ? "" : reqkeyobj.toString());
    }


    @Override
    public void onProgress(int bytesWritten, int totalSize) {
    onPgress(bytesWritten, totalSize);
    }


    @Override
    public void onFinish() {
    onReqFinish();
    }
    });
    }


    public void didDownloadFileObject(Context context, String target,
    String url, String reqKey, String tagcontent) {
    RequestParamesEntity rpe = new RequestParamesEntity();
    rpe.setContext(context);
    rpe.setTarget(target);
    rpe.setUrl(url);
    rpe.setReqKey(reqKey);
    rpe.setTagContent(tagcontent);
    mhandler.obtainMessage(DOWNLOAD_FILE_OBJECT, rpe).sendToTarget();
    }


    public void didDownloadFileObject(Context context, String target, String url) {
    didDownloadFileObject(context, target, url, "", "");
    }


    private class RequestParamesEntity {
    private Context context = null;
    private String target = "";
    private String url = "";
    private RequestParams params = null;
    private String reqKey = "";
    private String postContent = "";
    private String tagContent = "";


    /**
    * @return 获取context
    */
    public Context getContext() {
    return context;
    }


    /**
    * @param 设置context
    */
    public void setContext(Context context) {
    this.context = context;
    }


    /**
    * @return 获取target
    */
    public String getTarget() {
    return target;
    }


    /**
    * @param 设置target
    */
    public void setTarget(String target) {
    this.target = target;
    }


    /**
    * @return 获取url
    */
    public String getUrl() {
    return url;
    }


    /**
    * @param 设置url
    */
    public void setUrl(String url) {
    this.url = url;
    }


    /**
    * @return 获取params
    */
    public RequestParams getParams() {
    return params;
    }


    /**
    * @param 设置params
    */
    public void setParams(RequestParams params) {
    this.params = params;
    }


    /**
    * @return 获取reqKey
    */
    public String getReqKey() {
    return reqKey;
    }


    /**
    * @param 设置reqKey
    */
    public void setReqKey(String reqKey) {
    this.reqKey = reqKey;
    }


    /**
    * @return 获取postContent
    */
    public String getPostContent() {
    return postContent;
    }


    /**
    * @param 设置postContent
    */
    public void setPostContent(String postContent) {
    this.postContent = postContent;
    }


    /**
    * @return 获取tagContent
    */
    public String getTagContent() {
    return tagContent;
    }


    /**
    * @param 设置tagContent
    */
    public void setTagContent(String tagContent) {
    this.tagContent = tagContent;
    }
    }


    private class AsyncHttpClientOverride extends AsyncHttpClient {


    public AsyncHttpClientOverride(boolean fixNoHttpResponseException,
    int httpPort, int httpsPort) {
    super(fixNoHttpResponseException, httpPort, httpsPort);
    }


    @Override
    public void setEnableRedirects(final boolean enableRedirects) {
    ((DefaultHttpClient) getHttpClient())
    .setRedirectHandler(new DefaultRedirectHandler() {
    @Override
    public boolean isRedirectRequested(
    HttpResponse response, HttpContext context) {
    // int statusCode = response.getStatusLine()
    // .getStatusCode();
    // if (statusCode == 301 || statusCode == 302) {
    // return enableRedirects;
    // }
    return enableRedirects;
    }
    });
    }
    }


    private void sendUnLoginBroadcast(Context context) {
    Intent mintent = new Intent(ConstEnum.UnLoginBroadcastAction.getValue());
    context.sendBroadcast(mintent);
    }


    /**
    * 避免在线程中做http请求
    */
    private Handler mhandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    switch (msg.what) {
    case POST_REQUEST_OBJECT:
    postRequestObject(msg.obj);
    break;
    case POST_XML_REQUEST_OBJECT:
    postXmlRequestObject(msg.obj);
    break;
    case GET_REQUEST_OBJECT:
    getRequestObject(msg.obj);
    break;
    case DOWNLOAD_FILE_OBJECT:
    didDownloadFileObject(msg.obj);
    break;
    }
    }
    };
    }

你可能感兴趣的:(android)