java 一个http客户端,不仅可以处理同步请求,还可以处理异步请求。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 一个http客户端,不仅可以处理同步请求,还可以处理异步请求。相关的知识,希望对你有一定的参考价值。

public class RestapiRes<T> {
	private T data;
	private String description;
	private Integer status;
	private String msg;
	private Exception exception = null;
	private int httpCode = 200;    // 默认ok


	public T getData() {
		return data;
	}
	public void setData(T data) {
		this.data = data;
	}

	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}

	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	
	public Exception getException() {
		return exception;
	}
	public void setException(Exception exception) {
		this.exception = exception;
	}

	public int getHttpCode() {
		return httpCode;
	}
	public void setHttpCode(int httpCode) {
		this.httpCode = httpCode;
	}
}
public class HttpClient {
	private DefaultHttpClient client;
	private Handler commonHandler = null;
	
	private abstract class CommonCb {
		protected abstract void exe();
		
		public final void runExe() {
			exe();
		}
	}

	public final ExecutorService THREADPOOL_EXECUTOR = Executors.newCachedThreadPool();

	public HttpClient() {
		commonHandler = new Handler(new Callback() {
			@Override
			public boolean handleMessage(Message msg) {
				CommonCb cb = (CommonCb) msg.obj;
				cb.runExe();

				return true;
			}
		});

		HttpParams params = new BasicHttpParams();
		ConnManagerParams.setMaxTotalConnections(params, 100);
		ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(100));
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setUserAgent(params, "XXX-Client");
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, false);
		HttpConnectionParams.setConnectionTimeout(params, BaseConstants.HTTPCLIENT_TIMEOUT_MS);
		HttpConnectionParams.setSoTimeout(params, BaseConstants.HTTPCLIENT_TIMEOUT_MS);

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

		ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
		client = new DefaultHttpClient(cm, params);
	}

	public void setMaxConnectionsPerRoute(int maxConnectionPerRoute) {
		if (maxConnectionPerRoute <= 0) {
			throw new IllegalArgumentException("maxConnectionPerRoute = " + maxConnectionPerRoute);
		}

		HttpParams httpParameters = client.getParams();
		ConnManagerParams.setMaxConnectionsPerRoute(httpParameters, new ConnPerRouteBean(maxConnectionPerRoute));
	}

	public void setMaxTotalConnections(int maxTotalConnections) {
		if (maxTotalConnections <= 0) {
			throw new IllegalArgumentException("maxTotalConnections = " + maxTotalConnections);
		}

		HttpParams httpParameters = client.getParams();
		ConnManagerParams.setMaxTotalConnections(httpParameters, maxTotalConnections);
	}

	public void setSocketTimeout(int timeout) {
		if (timeout <= 0) {
			throw new IllegalArgumentException("timeout = " + timeout);
		}

		HttpParams httpParameters = client.getParams();
		HttpConnectionParams.setSoTimeout(httpParameters, timeout);
	}

	public void setConnectTimeout(int timeout) {
		if (timeout <= 0) {
			throw new IllegalArgumentException("timeout = " + timeout);
		}

		HttpParams httpParameters = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
	}

	public int postReturnHttpCode(String url, Map<String, Object> parameters) throws ClientProtocolException, IOException {
		HttpPost httppost = new HttpPost(url);
	
		try {
			List<NameValuePair> data = buildPostData(parameters);
			UrlEncodedFormEntity e = new UrlEncodedFormEntity(data, HTTP.UTF_8);
			e.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httppost.setEntity(e);
			HttpResponse httpResponse = client.execute(httppost);
			int ret = httpResponse.getStatusLine().getStatusCode();

			if (DEBUG) {
				Log.i(TAG_PREFIX + "httpclient log", "url=" + url + ", data=" + data + " , response=" + ret);
			}

			return ret;
		} finally {
			httppost.abort();
		}
	}

	public <T> T post(String url, Map<String, Object> parameters, CallBack<T> callback) throws ClientProtocolException, IOException {
		String ret = post(url, parameters, (Integer) null);
	
		return callback.call(ret);
	}

	public <D> void postAsyn(final String url, final Map<String, Object> parameters, final TypeToken<? extends RestapiRes<D>> t, final AsyncTaskPostExe<RestapiRes<D>> asyncTaskPostExe) {
		THREADPOOL_EXECUTOR.execute(new Runnable() {
			@Override
			public void run() {
				RestapiRes<D> finalret = null;

				try {
					String ret = post(url, parameters, (Integer) null);
					Type type = t.getType();
					finalret = Gson.getInstance().fromJson(ret, type);
				} catch (NoHttpResponseException e) {
					Object object = parameters.get("retry");
					if (object != null && ((Integer) object) > 0) {
						parameters.put("retry", ((Integer) object) - 1);
						postAsyn(url, parameters, t, asyncTaskPostExe);
						return;
					}

					Log.e(getLogTag(), "" + url + "|" + parameters, e);

					if (finalret == null) {
						finalret = new RestapiRes<D>();
					}

					finalret.setException(e);
					finalret.setHttpCode(500);
				} catch (Exception e) {
					Log.e(getLogTag(), "" + url + "|" + parameters, e);
				
					if (finalret == null) {
						finalret = new RestapiRes<D>();
					}
				
					finalret.setException(e);
					finalret.setHttpCode(500);
				}

				final RestapiRes<D> finalret2 = finalret;

				commonHandler.obtainMessage(0, new CommonCb() {
					@Override
					public void exe() {
						if (asyncTaskPostExe != null) {
							asyncTaskPostExe.runExecute(finalret2);
						}
					}
				}).sendToTarget();
			}
		});
	}

	public String post(String url, Map<String, Object> parameters, Integer timeoutms) throws ClientProtocolException, IOException {
		HttpPost httppost = new HttpPost(url);
		
		if (timeoutms != null) {
			HttpParams httpParams = httppost.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, timeoutms);
			HttpConnectionParams.setSoTimeout(httpParams, timeoutms);
			httppost.setParams(httpParams);
		}

		httppost.addHeader("Referer", "http://xxx.com");
		
		try {
			List<NameValuePair> data = buildPostData(parameters);
			UrlEncodedFormEntity e = new UrlEncodedFormEntity(data, HTTP.UTF_8);
			e.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httppost.setEntity(e);
			HttpResponse httpResponse = client.execute(httppost);
			HttpEntity entity = httpResponse.getEntity();
			String ret = EntityUtils.toString(entity, HTTP.UTF_8);

			return ret;
		} catch (Exception e) {
			Log.e(getLogTag(), "" + url + "|" + parameters, e);

			if (e instanceof ClientProtocolException) {
				throw (ClientProtocolException) e;
			} else if (e instanceof IOException) {
				throw (IOException) e;
			} else {
				throw new RuntimeException("", e);
			}
		} finally {
			httppost.abort();
		}
	}

	public <T> T get(String url, CallBack<T> callback) throws ClientProtocolException, IOException {
		String ret = get(url, (Integer)null);

		return callback.call(ret);
	}

	public int getReturnHttpCode(String url) throws ClientProtocolException, IOException {
		HttpGet httpget = new HttpGet(url);
	
		try {
			HttpResponse httpResponse = client.execute(httpget);
	
			int ret = httpResponse.getStatusLine().getStatusCode();

			return ret;
		} finally {
			httpget.abort();
		}
	}

	public String get(String url, Integer timeoutms) throws ClientProtocolException, IOException {	
		HttpGet httpget = new HttpGet(url);
		
		if (timeoutms != null) {
			HttpParams httpParams = httpget.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, timeoutms);
			HttpConnectionParams.setSoTimeout(httpParams, timeoutms);
		}
		
		try {
			HttpResponse httpResponse = client.execute(httpget);
			HttpEntity entity = httpResponse.getEntity();
			String ret = EntityUtils.toString(entity, HTTP.UTF_8);

			return ret;
		} finally {
			httpget.abort();
		}
	}

	private List<NameValuePair> buildPostData(Map<String, Object> para) {
		if (para == null || para.size() == 0) {
			return new ArrayList<NameValuePair>(0);
		}
	
		List<NameValuePair> ret = new ArrayList<NameValuePair>(para.size());

		for (String key : para.keySet()) {
			Object p = para.get(key);

			if (p == null || key == null) {
				continue;
			}
				
			String v = p.toString();
			if (p instanceof java.util.Date) {
				v = DateUtil.getStringFromDate((Date) p, "yyyy-MM-dd HH:mm:ss");
			}
			if (key != null && p != null) {
				NameValuePair np = new BasicNameValuePair(key, v);

				ret.add(np);
			}
		}

		return ret;
	}

	public HttpResponse getResponse(String url) throws IOException {
		HttpGet httpget = new HttpGet(url);
		HttpResponse httpResponse = client.execute(httpget);
	
		return httpResponse;
	}

	public HttpResponse postResponse(String url, Map<String, Object> parameters) throws IOException {
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> data = buildPostData(parameters);
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, HTTP.UTF_8);
		entity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
		httppost.setEntity(entity);
		HttpResponse httpResponse = client.execute(httppost);
	
		return httpResponse;
	}

	public void clearCookies() {
		client.getCookieStore().clear();
	}

	public List<Cookie> getCookies() {
		return client.getCookieStore().getCookies();
	}
	
	public void addCookie(String key, String value, String domain){
		addCookie(key, value, domain, null);
	}
	
	public void addCookie(String key, String value, String domain, Date expiryDate){
		BasicClientCookie cookie = new BasicClientCookie(key, value);
	
		if (domain == null) {
			domain = "xxx.com";
		}

		cookie.setDomain(domain);
		cookie.setPath("/");
		if (expiryDate != null) {
			cookie.setExpiryDate(expiryDate);
		}

		client.getCookieStore().addCookie(cookie); 
	}

	public DefaultHttpClient getHttpClient() {
		return client;
	}

	public Cookie findCookie(List<Cookie> cookies, String name){
		return findCookie(cookies, name, null);
	}
	
	public Cookie findCookie(List<Cookie> cookies, String name, String domain){
		List<Cookie> ret = new ArrayList<Cookie>();
	
		if (cookies != null) {
			if (domain == null) {
				for (Cookie c : cookies) {
					if (c.getName().equals(name)) {
						ret.add(c);
					}
				}
			} else {
				for (Cookie c : cookies) {
					if (c.getName().equals(name) && c.getDomain().equals(domain)) {
						ret.add(c);
					}
				}
			}
			
		}

		if (ret.size() > 1) {
			Log.e(getLogTag(), "cookie err:" + name + " has multi values");

			return ret.get(0);
		} else if (ret.size() == 1) {
			return ret.get(0);
		} else {
			return null;
		}
	}

	public void downloadSyn(String url, OutputStream outputStream) throws Exception {
		BufferedInputStream input = null;

		try {
			final HttpGet hGet = new HttpGet(url);
			HttpResponse response;
			response = client.execute(hGet);
			StatusLine line = response.getStatusLine();
		
			if(line.getStatusCode() != HttpStatus.SC_OK){
				throw new Exception("HttpStatus not ok");
			}
		
			HttpEntity entity = response.getEntity();
			input = new BufferedInputStream(entity.getContent());
			byte b[] = new byte[1024];
			int j = 0;
			while ((j = input.read(b)) != -1) {
				outputStream.write(b, 0, j);
			}
		} finally {
			IOUtils.closeQuietly(input);
		}
	}
}
public class HcFactory {
	private static HttpClient hc = null;


	private HcFactory() {}

	public static synchronized HttpClient getGlobalHc() {
		if (hc == null) {
			hc = new HttpClient();
		}

		return hc;
	}
}
public interface Callback<T> {
	 public T call(String response);
}
public abstract class AsyncTaskPostExe<T> {
	private Object token = null;


	public AsyncTaskPostExe() {}

	public AsyncTaskPostExe(Object token) {
		this.token = token;
	}

	public final void runExecute(final T t) {
		if (token != null) {
			onPostExecute(t, token);
		} else {
			onPostExecute(t);
		}
	}

	protected void onPostExecute(T t) {}
	protected void onPostExecute(T t, Object token) {}
}

以上是关于java 一个http客户端,不仅可以处理同步请求,还可以处理异步请求。的主要内容,如果未能解决你的问题,请参考以下文章

jdk11新特性——标准Java异步HTTP客户端

(05)使用DeferredResult多线程异步处理请求

(05)使用DeferredResult多线程异步处理请求

HTTP请求中同步与异步有啥不同

使用HTTP的同步方式还是异步方式?

Linux(程序设计):65---同步HTTP请求异步HTTP请求