Http 设置超时 + X509协议
来源:互联网 发布:小规模纳税人 知乎 编辑:程序博客网 时间:2024/05/04 11:04
POST
URL, PARAMS 分开发送
public class HttpClient {private static final AllowAllHostnameVerifier HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();private static X509TrustManager xtm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};private static X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };static String paths = "";static Map<String, String> paramss = null;static String encodings = "";// static String bakold = "";static String RetBak = "";static boolean isRe = true;static int isStop = 0;// 增加捕获超时异常public static String sendPOSTRequestForInputStream(String path, Map<String, String> params, String encoding) throws ConnectTimeoutException {paths = path;paramss = params;encodings = encoding;// bakold = "";RetBak = "";isRe = true;isStop = 0;class acceptThread extends Thread {Map<String, String> paramsa = null;public acceptThread(Map<String, String> params) {this.paramsa = params;}InputStream in = null;private HttpsURLConnection conn = null;@Overridepublic void run() {String bakn = "";try {StringBuilder entityBuilder = new StringBuilder("");if (paramsa != null && !paramss.isEmpty()) {for (Map.Entry<String, String> entry : paramss.entrySet()) {entityBuilder.append(entry.getKey()).append('=');entityBuilder.append(URLEncoder.encode(entry.getValue(), encodings));entityBuilder.append('&');}entityBuilder.deleteCharAt(entityBuilder.length() - 1);}byte[] entity = entityBuilder.toString().getBytes();URL url = new URL(paths);conn = (HttpsURLConnection) url.openConnection();if (conn instanceof HttpsURLConnection) {// Trust all certificatesSSLContext context = SSLContext.getInstance("TLS");context.init(new KeyManager[0], xtmArray, new SecureRandom());SSLSocketFactory socketFactory = context.getSocketFactory();conn.setSSLSocketFactory(socketFactory);conn.setHostnameVerifier(HOSTNAME_VERIFIER);}conn.setConnectTimeout(20000);// !!!!conn.setReadTimeout(20000);conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(entity.length));Log.i("PathInfo", paths + " " + entityBuilder.toString());OutputStream outStream = conn.getOutputStream();outStream.write(entity);outStream.flush();outStream.close();in = conn.getInputStream();int num = 0;byte[] resu = new byte[1024];// StringBuilder sb = new StringBuilder(); //异步StringBuffer sb = new StringBuffer(); // 同步while ((num = in.read(resu)) != -1) {bakn = new String(resu, 0, num);// RetBak += URLDecoder.decode(bakn, encodings);sb.append(URLDecoder.decode(bakn, encodings));}RetBak = sb.toString();in.close();Log.e("Return", RetBak);} catch (Exception e) {e.printStackTrace();RetBak = "";} finally {try {if (in != null) {in.close();}if (conn != null) {conn.disconnect();}} catch (IOException e) {e.printStackTrace();Log.e("CLOUD", "InvokeWebServiceHelper类中释放资源出错");}}isRe = false;}}acceptThread abc = new acceptThread(params);abc.start();while (isRe) {SystemClock.sleep(1);isStop++;if (isStop > 120000) {break;}}return RetBak;}}
GET
URL,PARAMS 放在头里一起发送
public class HttpClientGet {private static final AllowAllHostnameVerifier HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();private static X509TrustManager xtm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};private static X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };static String paths = "";static Map<String, String> paramss = null;static String encodings = "";static String RetBak = "";static boolean isRe = true;static int isStop = 0;// 增加捕获超时异常public static String sendPOSTRequestForInputStream(String path, Map<String, String> params, String encoding) throws ConnectTimeoutException {paths = path;paramss = params;encodings = encoding;RetBak = "";isRe = true;isStop = 0;class acceptThread extends Thread {Map<String, String> paramsa = null;public acceptThread(Map<String, String> params) {this.paramsa = params;}private HttpsURLConnection conn = null;InputStream in = null;@Overridepublic void run() {String bakn = "";try {StringBuilder entityBuilder = new StringBuilder("");if (paramsa != null && !paramss.isEmpty()) {for (Map.Entry<String, String> entry : paramss.entrySet()) {entityBuilder.append(entry.getKey()).append('=');entityBuilder.append(URLEncoder.encode(entry.getValue(), encodings));entityBuilder.append('&');}entityBuilder.deleteCharAt(entityBuilder.length() - 1);}String httpurl = paths + entityBuilder.toString();Log.i("AMDownLoad", "httpurl_GET" + httpurl);URL url = new URL(httpurl);conn = (HttpsURLConnection) url.openConnection();if (conn instanceof HttpsURLConnection) {// Trust all certificatesSSLContext context = SSLContext.getInstance("TLS");context.init(new KeyManager[0], xtmArray, new SecureRandom());SSLSocketFactory socketFactory = context.getSocketFactory();conn.setSSLSocketFactory(socketFactory);conn.setHostnameVerifier(HOSTNAME_VERIFIER);}conn.setConnectTimeout(15000);conn.setReadTimeout(15000);conn.setDoInput(true);conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "text/html");// conn.setRequestProperty("Content-Type",// "application/x-www-form-urlencoded");conn.setRequestProperty("Accept-Charset", encodings);conn.setRequestProperty("contentType", encodings);in = conn.getInputStream();int num = 0;byte[] resu = new byte[1024];StringBuffer sb = new StringBuffer(); // 同步while ((num = in.read(resu)) != -1) {bakn = new String(resu, 0, num);sb.append(URLDecoder.decode(bakn, encodings));}RetBak = sb.toString();Log.e("Return", RetBak);} catch (Exception e) {e.printStackTrace();RetBak = "";} finally {try {if (in != null) {in.close();}if (conn != null) {conn.disconnect();}} catch (IOException e) {e.printStackTrace();Log.e("CLOUD", "InvokeWebServiceHelper类中释放资源出错");}}isRe = false;}}acceptThread abc = new acceptThread(params);abc.start();while (isRe) {SystemClock.sleep(1);isStop++;if (isStop > 120000) {break;}}return RetBak;}}
Defalt 方法
POST
private Runnable runnable = new Runnable() { @Override public void run() { String url = BaseServicesInfo.SERVER_BASE_PATH + fileName; HttpPost httpRequest = new HttpPost(url); try{ HttpEntity entity = new UrlEncodedFormEntity(params); httpRequest.setEntity(entity); HttpClient client = new DefaultHttpClient(); // 请求超时 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); // 读取超时 client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000 ); HttpResponse response = client.execute(httpRequest); if(response.getStatusLine().getStatusCode() == 200){ str = EntityUtils.toString(response.getEntity()); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", str); msg.setData(data); handler.sendMessage(msg); }else{ str = String.valueOf(response.getStatusLine().getStatusCode()); Message msg = new Message(); Bundle data = new Bundle(); data.putString("error", str); msg.setData(data); handler.sendMessage(msg); } }catch(Exception e){ e.printStackTrace(); Message msg = new Message(); Bundle data = new Bundle(); data.putString("error", str); msg.setData(data); handler.sendMessage(msg); } } };
GET
Runnable runnable = new Runnable() { @Override public void run() { HttpURLConnection conn = null; InputStream inputStream = null; try { URL url = new URL(baseUrl); conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(8000); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "text/html"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("contentType", "utf-8"); inputStream = conn.getInputStream(); byte[] buffer = null; if(conn.getResponseCode() == 200){ buffer = new byte[1024]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = inputStream.read(buffer)) != -1) { out.write(buffer, 0, len); } buffer = out.toByteArray(); } mCallback.HandleAsync(buffer); SendMsg("value",buffer); } catch (Exception e) { e.printStackTrace(); Log.e("sjr","Network-error"); } finally{ try { if(inputStream != null){ inputStream.close(); } if(conn != null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); Log.e("sjr","InvokeWebServiceHelper类中释放资源出错"); } } } };
- Http 设置超时 + X509协议
- HTTP 设置超时
- http 超时设置
- Http超时设置
- http超时设置
- java设置http超时时间
- http 请求 超时时间设置
- 如何在Http连接中设置超时?
- Java HTTP请求时设置超时
- Android http请求数据 设置超时
- android Http 网络超时,怎么设置
- python http,或者soap设置超时时间
- Android http连接设置超时无效
- 设置HTTP请求超时自动重发
- Go语言http.Get()超时设置
- HTTP Get和Post请求设置超时
- 为ServerXMLHTTP对象的HTTP请求设置超时时间
- 为ServerXMLHTTP对象的HTTP请求设置超时时间
- ZOJ 3471 Most Powerful
- STM32 USB 问题汇总
- css基础---小结
- C++获取文件夹下的所有文件名
- Acey.Excel简介--简单高效的Excel组件
- Http 设置超时 + X509协议
- 触摸屏驱动
- 不同进制之间的转换的各种方法
- 线程同步的一些方法
- OC学习之封装,继承初解
- Junk-Mail Filter
- OC学习之多态初解
- android面试
- USB 描述符详细解析,来自老外网站,比协议描述清晰