AsyncHttpClient 这个类库可以在Java应用程序中执行HTTP 请求并异步处理HTTP响应。用法非常简单。
项目如图:
源码分析:
public class AsyncHttpResponseHandler { //请求返回处理 成功 失败 开始 完成 等自定义的消息
public class BinaryHttpResponseHandler extends AsyncHttpResponseHandler { //字节流返回处理 该库用于处理图片等
public class JsonHttpResponseHandler extends AsyncHttpResponseHandler { //json请求返回处理 服务器与客户端用json交流时使用
class AsyncHttpRequest implements Runnable { //基于线程 异步请求 通过AsyncHttpResponseHandler回调
public class PersistentCookieStore implements CookieStore { //HttpClient处理数据 使用cookie持久性存储接口
public class RequestParams { //封装了参数处理 例如:
* RequestParams params = new RequestParams();
* params.put("username", "james");
* params.put("password", "123456");
* params.put("email", "my@email.com");
* params.put("profile_picture", new File("pic.jpg")); // Upload a File
* params.put("profile_picture2", someInputStream); // Upload an InputStream
* params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
*
* AsyncHttpClient client = new AsyncHttpClient();
* client.post("http://myendpoint.com", params, responseHandler);
class RetryHandler implements HttpRequestRetryHandler {//多个线程同步处理
public class SerializableCookie implements Serializable { //操作cookie 放入/取出数据
class SimpleMultipartEntity implements HttpEntity { //处理多个请求实体封装
public abstract class SyncHttpClient extends AsyncHttpClient { //同步客户端请求
public class AsyncHttpClient { //异步客户端请求 如:
* AsyncHttpClient client = new AsyncHttpClient();
* client.get("http://www.google.com", new AsyncHttpResponseHandler() {
* @Override
* public void onSuccess(String response) {
* System.out.println(response);
* }
* });
操作实例如:
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}