package net.dreamlu.api.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang.StringUtils; public class HttpKit { private static final String DEFAULT_CHARSET = "UTF-8"; // 默认字符集 private static final String _GET = "GET"; // GET private static final String _POST = "POST";// POST /** * 初始化http请求参数 * @param url * @param method * @param headers * @return * @throws IOException */ private static HttpURLConnection initHttp (String url, String method, Map<String, String> headers) throws IOException { URL _url = new URL(url); HttpURLConnection http = (HttpURLConnection) _url.openConnection(); // 连接超时 http.setConnectTimeout(25000); // 读取超时 --服务器响应比较慢,增大时间 http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; } /** * 初始化http请求参数 * @param url * @param method * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ private static HttpsURLConnection initHttps (String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL _url = new URL(url); HttpsURLConnection http = (HttpsURLConnection) _url.openConnection(); // 设置域名校验 http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier()); // 连接超时 http.setConnectTimeout(25000); // 读取超时 --服务器响应比较慢,增大时间 http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; } /** * * @description * 功能描述: get 请求 * @return 返回类型: */ public static String get(String url, Map<String, String> params, Map<String, String> headers) { StringBuffer bufferRes = null; try { HttpURLConnection http = null; if (isHttps(url)) { http = initHttps(initParams(url, params), _GET, headers); } else { http = initHttp(initParams(url, params), _GET, headers); } InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } read.close(); in.close(); if (http != null) { http.disconnect();// 关闭连接 } return bufferRes.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * * @description * 功能描述: get 请求 * @return 返回类型: */ public static String get(String url) { return get(url, null); } /** * * @description * 功能描述: get 请求 * @return 返回类型: * @throws UnsupportedEncodingException */ public static String get(String url, Map<String, String> params) { return get(url, params, null); } /** * * @description * 功能描述: POST 请求 * @return 返回类型: */ public static String post(String url, String params, Map<String, String> headers) { StringBuffer bufferRes = null; try { HttpURLConnection http = null; if (isHttps(url)) { http = initHttps(url, _POST, headers); } else { http = initHttp(url, _POST, headers); } OutputStream out = http.getOutputStream(); out.write(params.getBytes(DEFAULT_CHARSET)); out.flush(); out.close(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } read.close(); in.close(); if (http != null) { http.disconnect();// 关闭连接 } return bufferRes.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * post map 请求 * @param url * @param params * @return * @throws UnsupportedEncodingException */ public static String post(String url, Map<String, String> params) throws UnsupportedEncodingException { return post(url, map2Url(params), null); } /** * post map 请求,headers请求头 * @param url * @param params * @return * @throws UnsupportedEncodingException */ public static String post(String url, Map<String, String> params, Map<String, String> headers) throws UnsupportedEncodingException { return post(url, map2Url(params), headers); } /** * * @description * 功能描述: 构造请求参数 * @return 返回类型: * @throws UnsupportedEncodingException */ public static String initParams(String url, Map<String, String> params) throws UnsupportedEncodingException { if (null == params || params.isEmpty()) { return url; } StringBuilder sb = new StringBuilder(url); if (url.indexOf("?") == -1) { sb.append("?"); } sb.append(map2Url(params)); return sb.toString(); } /** * map构造url * @description * 功能描述: * @return 返回类型: * @throws UnsupportedEncodingException */ public static String map2Url(Map<String, String> paramToMap) throws UnsupportedEncodingException { if (null == paramToMap || paramToMap.isEmpty()) { return null; } StringBuffer url = new StringBuffer(); boolean isfist = true; for (Entry<String, String> entry : paramToMap.entrySet()) { if (isfist) { isfist = false; } else { url.append("&"); } url.append(entry.getKey()).append("="); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { url.append(URLEncoder.encode(value, DEFAULT_CHARSET)); } } return url.toString(); } /** * 检测是否https * @param url */ private static boolean isHttps (String url) { return url.startsWith("https"); } /** * https 域名校验 * @param url * @param params * @return */ public class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true;// 直接返回true } } } // 证书管理 class MyX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }
相关推荐
UploadFileUtil工具类可以针对各种文件(图片、声音)进行httpConnection 上传
Java建立HttpConnection连接的例子,支持在手机端运行的的Java小程序,通过建立HttpConnection连接,获取到文本信息并显示在屏幕上,相关的测试代码如下: ContentConnection connection = (ContentConnection) ...
相信大家在调用rest webservice通常使用httpclient.该示例代码是使用httpconnection的形式,以POST和GET两种方式提交调用REST WebService。在项目中一直使用的工具类,分享给大家
通过HttpConnection请求跨域接口 public String invokeServiceMethod(String url,Map,String> params,Map, String> header) throws Exception{ HttpClient httpclient=new DefaultHttpClient(); HttpResponse...
android中利用httpconnection上传文件。可以选择要上传文件的路径,上传网址
java 基于https请求httpconnection, 在代码中加入tls, tls1.2等..
、矩形 Rectangle)和三角形( ( Triangle)等的绘图工具类,每个几何图形均具有绘制方法daw()和擦除方法 erase(),要求在绘制不支持的几何图形时,抛出一个 UnsupportedShapeException异常。绘制类图并编程模拟实现。 ②...
handy包 http://blog.csdn.net/facepp/article/details/7439840
Android用HttpConnection访问网络时实现类似浏览器自动保持上一次会话的功能
NULL 博文链接:https://wangxc.iteye.com/blog/591160
细心的开发者可能会发现,在用浏览器访问http时一般都会自动保持同一个会话,而用代码访问http连接时则每一次访问都会新建一个会话,那么我趁着这几天休假就把之前从网上资料中整理出的一个demo分享出来,实现安卓...
利用HTTPConnection类设置文件上传,这里没有搭建服务器端代码,因为太简单了...
# struts-scan 快速检测struts命令执行漏洞,可批量。 # 运行环境 MAC/Linux下的Python2 # 支持对以下版本的检测 ...此工具仅限于漏洞验证,如若使用者引起相关的法律责任请自负,开发者不承担连带责任。
建立HTTP连接请求
... ... 创建HTTP请求处理类:创建一个继承自http.server.BaseHTTPRequestHandler的...创建HTTP连接:使用http.client.HTTPConnection类创建一个HTTP连接对象,指定目标主机和端口。 发送HTTP请求:使用HTTP连接对象的req
代码包含了httpurlconnection基本操作,一些正常的操作。
Android文件断点下载,使用HttpConnection
本例演示最简单的android客户端和服务器端通信,客户端使用android4.0以上版本,服务器端为dynamic web project工程,使用时将client...因为android6.0以上不再支持httpclient通信,故本例使用HttpURLConnection类演示
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191) at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80) at ...
安卓下载工具工程代码,使用HttpConnection,不是使用系统自带的DownloadManager,方便监听下载状态。使用handler发送进度、异常消息。