Android:使用HttpClient访问HTTP/HTTPS服务器
2016-11-16 11:58
429 查看
网络请求类:
处理网络请求的子线程:
线程池工具类:
调用:
public class NetworkConnector { private static final int TIMEOUT = 10 * 1000; private static DefaultHttpClient getHttpClient() { try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpProtocolParams.setUserAgent(params, null); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SslSocketFactory customSSLSocketFactory = SslSocketFactory.getSocketFactory(); customSSLSocketFactory.setHostnameVerifier(SslSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("https", customSSLSocketFactory, 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient client = new DefaultHttpClient(manager, params); return client; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } } public synchronized static ResponseInfo execute(String url, byte[] buff, Map<String, String> headers) { DefaultHttpClient httpClient = getHttpClient(); int responseCode = 0; InputStream in = null; try { HttpPost request = new HttpPost(url); if (headers != null && !headers.isEmpty()) { Iterator it = headers.keySet().iterator(); String key = null; while (it.hasNext()) { key = it.next().toString(); request.setHeader(key, headers.get(key)); } } request.setHeader("Content-Type", "application/octet-stream; charset=utf-8"); HttpEntity entity = new ByteArrayEntity(buff); request.setEntity(entity); HttpResponse response = httpClient.execute(request); responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200 || responseCode == 201) { InputStream resIn = response.getEntity().getContent(); int len = (int) response.getEntity().getContentLength(); if (resIn != null && len > 0) { BufferedInputStream bufIn = new BufferedInputStream(resIn); byte[] data = new byte[len]; bufIn.read(data, 0, len); return new ResponseInfo(0, getHeaders(response.getAllHeaders()), data); } } } catch (Exception e) { e.printStackTrace(); if (responseCode != 200) { try { if (in != null) { in.close(); } httpClient.getConnectionManager().shutdown(); } catch (IOException e1) { e1.printStackTrace(); } } } finally { try { if (in != null) { in.close(); } httpClient.getConnectionManager().shutdown(); } catch (IOException e) { e.printStackTrace(); } } return null; } private static Map<String, String> getHeaders(Header[] headerArr) { Map<String, String> headerMap = new HashMap<>(); if (headerArr != null) { for (Header header : headerArr) { headerMap.put(header.getName(), header.getValue()); } } return headerMap; } }
处理网络请求的子线程:
public class RequestRunnable implements Runnable { private BaseRequest.RequestCallback listener; private byte[] buf; private String urlString; private boolean isRun; private Map<String, String> headers; private int apiId; public RequestRunnable(int apiId, String urlString, byte[] buf, Map<String, String> headers, BaseRequest.RequestCallback listener) { this.isRun = true; this.urlString = urlString; this.buf = buf; this.headers = headers; this.listener = listener; this.apiId = apiId; } public void cancelRequest() { this.isRun = false; } @Override public void run() { ResponseInfo response = NetworkConnector.execute(urlString, this.buf, headers); if (response != null) { response.apiId = apiId; } if (isRun) { Message msg = new Message(); msg.obj = response; msg.what = 1; mHandler.sendMessage(msg); } } private Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: if (msg.obj != null) { listener.onResponse((ResponseInfo) msg.obj); } else { listener.onErrorResponse(apiId); } break; } } }; }
线程池工具类:
public class ThreadPoolUtil { private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1; private static int MAX_POOL_SIZE = CORE_POOL_SIZE * 2 + 1; private static int KEEP_ALIVE_TIME = 60 * 10; private static BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(128); private static ThreadPoolExecutor threadPool; private ThreadPoolUtil() { } static { threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, new ThreadFactory() { private final AtomicInteger integer = new AtomicInteger(); @Override public Thread newThread(Runnable r) { return new Thread(r, "thread:" + integer.getAndIncrement()); } }); } public static void execute(Runnable runnable) { threadPool.execute(runnable); } }
调用:
/** * 调用 * @param apiId 接口id * @param url 服务器url * @param buf 需要上传的字节数组 */ protected final void requestData(int apiId, String url, byte[] buf) { ThreadPoolUtil.execute(new RequestRunnable(apiId, url, buf, getHeaders(), this)); }
相关文章推荐
- Android中使用https(HTTP+SSL)访问服务器
- Android中使用HttpURLConnection和HttpClient实现GET和POST请求访问网络
- Android网络访问之http、https、 cookie的使用
- Linux下SVN服务器同时支持Apache的http和https及svnserve独立服务器三种模式且使用相同的访问权限账号
- http(16):如何使用HttpClient库用代码访问服务器
- 使用SVN管理VC项目(解决无法访问https://code.google.com/hosting/settings)(服务器为Code Google)(转http://blog.csdn.net/xiadasong007/archive/2010/07/
- [Android实例] Android 使用HttpClient访问https
- Android中使用httpclient访问服务器,需要session功能
- 分享:Android 客户端使用HttpGet访问服务器
- Android在使用HttpClient访问https时认证策略
- 【异常】Android中使用localhost:8080或者172.0.0.1:8080访问本地服务器org.apache.http.conn.HttpHostConnectException异常
- HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection
- Android使用httpclient访问http
- Android使用Http访问并解析服务器XML数据
- Android网络编程 HttpURLConnection,HttpClient,Asynchttpclient使用
- Android访问网络,使用HttpURLConnection还是HttpClient?
- UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器
- 让apache服务器可以保证http和https同时访问(解决https可以访问而http不能访问)