HTTP与HTTPS区别:http://blog.csdn.net/lyhjava/article/details/51860215

URL发送 HTTP、HTTPS:http://blog.csdn.net/guozili1/article/details/53995121

HttpClient 发送 HTTP、HTTPS 请求的简单封装

http://blog.csdn.net/happylee6688/article/details/47148227

  1. <span style="font-family:Comic Sans MS;">import org.apache.commons.io.IOUtils;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpStatus;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  13. import org.apache.http.conn.ssl.SSLContextBuilder;
  14. import org.apache.http.conn.ssl.TrustStrategy;
  15. import org.apache.http.conn.ssl.X509HostnameVerifier;
  16. import org.apache.http.entity.StringEntity;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.DefaultHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23.  
  24. import javax.net.ssl.SSLContext;
  25. import javax.net.ssl.SSLException;
  26. import javax.net.ssl.SSLSession;
  27. import javax.net.ssl.SSLSocket;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.nio.charset.Charset;
  31. import java.security.GeneralSecurityException;
  32. import java.security.cert.CertificateException;
  33. import java.security.cert.X509Certificate;
  34. import java.util.ArrayList;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;
  38.  
  39. /**
  40. * HTTP 请求工具类
  41. *
  42. * @author : liii
  43. * @version : 1.0.
  44. * @date : //
  45. * @see : TODO
  46. */
  47. public class HttpUtil {
  48. private static PoolingHttpClientConnectionManager connMgr;
  49. private static RequestConfig requestConfig;
  50. private static final int MAX_TIMEOUT = ;
  51.  
  52. static {
  53. // 设置连接池
  54. connMgr = new PoolingHttpClientConnectionManager();
  55. // 设置连接池大小
  56. connMgr.setMaxTotal();
  57. connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
  58.  
  59. RequestConfig.Builder configBuilder = RequestConfig.custom();
  60. // 设置连接超时
  61. configBuilder.setConnectTimeout(MAX_TIMEOUT);
  62. // 设置读取超时
  63. configBuilder.setSocketTimeout(MAX_TIMEOUT);
  64. // 设置从连接池获取连接实例的超时
  65. configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
  66. // 在提交请求之前 测试连接是否可用
  67. configBuilder.setStaleConnectionCheckEnabled(true);
  68. requestConfig = configBuilder.build();
  69. }
  70.  
  71. /**
  72. * 发送 GET 请求(HTTP),不带输入数据
  73. * @param url
  74. * @return
  75. */
  76. public static String doGet(String url) {
  77. return doGet(url, new HashMap<String, Object>());
  78. }
  79.  
  80. /**
  81. * 发送 GET 请求(HTTP),K-V形式
  82. * @param url
  83. * @param params
  84. * @return
  85. */
  86. public static String doGet(String url, Map<String, Object> params) {
  87. String apiUrl = url;
  88. StringBuffer param = new StringBuffer();
  89. int i = ;
  90. for (String key : params.keySet()) {
  91. if (i == )
  92. param.append("?");
  93. else
  94. param.append("&");
  95. param.append(key).append("=").append(params.get(key));
  96. i++;
  97. }
  98. apiUrl += param;
  99. String result = null;
  100. HttpClient httpclient = new DefaultHttpClient();
  101. try {
  102. HttpGet httpPost = new HttpGet(apiUrl);
  103. HttpResponse response = httpclient.execute(httpPost);
  104. int statusCode = response.getStatusLine().getStatusCode();
  105.  
  106. System.out.println("执行状态码 : " + statusCode);
  107.  
  108. HttpEntity entity = response.getEntity();
  109. if (entity != null) {
  110. InputStream instream = entity.getContent();
  111. result = IOUtils.toString(instream, "UTF-8");
  112. }
  113. } catch (IOException e) {
  114. e.printStackTrace();
  115. }
  116. return result;
  117. }
  118.  
  119. /**
  120. * 发送 POST 请求(HTTP),不带输入数据
  121. * @param apiUrl
  122. * @return
  123. */
  124. public static String doPost(String apiUrl) {
  125. return doPost(apiUrl, new HashMap<String, Object>());
  126. }
  127.  
  128. /**
  129. * 发送 POST 请求(HTTP),K-V形式
  130. * @param apiUrl API接口URL
  131. * @param params 参数map
  132. * @return
  133. */
  134. public static String doPost(String apiUrl, Map<String, Object> params) {
  135. CloseableHttpClient httpClient = HttpClients.createDefault();
  136. String httpStr = null;
  137. HttpPost httpPost = new HttpPost(apiUrl);
  138. CloseableHttpResponse response = null;
  139.  
  140. try {
  141. httpPost.setConfig(requestConfig);
  142. List<NameValuePair> pairList = new ArrayList<>(params.size());
  143. for (Map.Entry<String, Object> entry : params.entrySet()) {
  144. NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
  145. .getValue().toString());
  146. pairList.add(pair);
  147. }
  148. httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
  149. response = httpClient.execute(httpPost);
  150. System.out.println(response.toString());
  151. HttpEntity entity = response.getEntity();
  152. httpStr = EntityUtils.toString(entity, "UTF-8");
  153. } catch (IOException e) {
  154. e.printStackTrace();
  155. } finally {
  156. if (response != null) {
  157. try {
  158. EntityUtils.consume(response.getEntity());
  159. } catch (IOException e) {
  160. e.printStackTrace();
  161. }
  162. }
  163. }
  164. return httpStr;
  165. }
  166.  
  167. /**
  168. * 发送 POST 请求(HTTP),JSON形式
  169. * @param apiUrl
  170. * @param json json对象
  171. * @return
  172. */
  173. public static String doPost(String apiUrl, Object json) {
  174. CloseableHttpClient httpClient = HttpClients.createDefault();
  175. String httpStr = null;
  176. HttpPost httpPost = new HttpPost(apiUrl);
  177. CloseableHttpResponse response = null;
  178.  
  179. try {
  180. httpPost.setConfig(requestConfig);
  181. StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
  182. stringEntity.setContentEncoding("UTF-8");
  183. stringEntity.setContentType("application/json");
  184. httpPost.setEntity(stringEntity);
  185. response = httpClient.execute(httpPost);
  186. HttpEntity entity = response.getEntity();
  187. System.out.println(response.getStatusLine().getStatusCode());
  188. httpStr = EntityUtils.toString(entity, "UTF-8");
  189. } catch (IOException e) {
  190. e.printStackTrace();
  191. } finally {
  192. if (response != null) {
  193. try {
  194. EntityUtils.consume(response.getEntity());
  195. } catch (IOException e) {
  196. e.printStackTrace();
  197. }
  198. }
  199. }
  200. return httpStr;
  201. }
  202.  
  203. /**
  204. * 发送 SSL POST 请求(HTTPS),K-V形式
  205. * @param apiUrl API接口URL
  206. * @param params 参数map
  207. * @return
  208. */
  209. public static String doPostSSL(String apiUrl, Map<String, Object> params) {
  210. CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
  211. HttpPost httpPost = new HttpPost(apiUrl);
  212. CloseableHttpResponse response = null;
  213. String httpStr = null;
  214.  
  215. try {
  216. httpPost.setConfig(requestConfig);
  217. List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
  218. for (Map.Entry<String, Object> entry : params.entrySet()) {
  219. NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
  220. .getValue().toString());
  221. pairList.add(pair);
  222. }
  223. httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
  224. response = httpClient.execute(httpPost);
  225. int statusCode = response.getStatusLine().getStatusCode();
  226. if (statusCode != HttpStatus.SC_OK) {
  227. return null;
  228. }
  229. HttpEntity entity = response.getEntity();
  230. if (entity == null) {
  231. return null;
  232. }
  233. httpStr = EntityUtils.toString(entity, "utf-8");
  234. } catch (Exception e) {
  235. e.printStackTrace();
  236. } finally {
  237. if (response != null) {
  238. try {
  239. EntityUtils.consume(response.getEntity());
  240. } catch (IOException e) {
  241. e.printStackTrace();
  242. }
  243. }
  244. }
  245. return httpStr;
  246. }
  247.  
  248. /**
  249. * 发送 SSL POST 请求(HTTPS),JSON形式
  250. * @param apiUrl API接口URL
  251. * @param json JSON对象
  252. * @return
  253. */
  254. public static String doPostSSL(String apiUrl, Object json) {
  255. CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
  256. HttpPost httpPost = new HttpPost(apiUrl);
  257. CloseableHttpResponse response = null;
  258. String httpStr = null;
  259.  
  260. try {
  261. httpPost.setConfig(requestConfig);
  262. StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
  263. stringEntity.setContentEncoding("UTF-8");
  264. stringEntity.setContentType("application/json");
  265. httpPost.setEntity(stringEntity);
  266. response = httpClient.execute(httpPost);
  267. int statusCode = response.getStatusLine().getStatusCode();
  268. if (statusCode != HttpStatus.SC_OK) {
  269. return null;
  270. }
  271. HttpEntity entity = response.getEntity();
  272. if (entity == null) {
  273. return null;
  274. }
  275. httpStr = EntityUtils.toString(entity, "utf-8");
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. } finally {
  279. if (response != null) {
  280. try {
  281. EntityUtils.consume(response.getEntity());
  282. } catch (IOException e) {
  283. e.printStackTrace();
  284. }
  285. }
  286. }
  287. return httpStr;
  288. }
  289.  
  290. /**
  291. * 创建SSL安全连接
  292. *
  293. * @return
  294. */
  295. private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
  296. SSLConnectionSocketFactory sslsf = null;
  297. try {
  298. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  299.  
  300. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  301. return true;
  302. }
  303. }).build();
  304. sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
  305.  
  306. @Override
  307. public boolean verify(String arg0, SSLSession arg1) {
  308. return true;
  309. }
  310.  
  311. @Override
  312. public void verify(String host, SSLSocket ssl) throws IOException {
  313. }
  314.  
  315. @Override
  316. public void verify(String host, X509Certificate cert) throws SSLException {
  317. }
  318.  
  319. @Override
  320. public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
  321. }
  322. });
  323. } catch (GeneralSecurityException e) {
  324. e.printStackTrace();
  325. }
  326. return sslsf;
  327. }
  328.  
  329. /**
  330. * 测试方法
  331. * @param args
  332. */
  333. public static void main(String[] args) throws Exception {
  334.  
  335. }
  336. }</span>

显示

JAVA HTTP请求和HTTPS请求的更多相关文章

  1. python——请求服务器(http请求和https请求)

    一.http请求 1.http请求方式:get和post get一般用于获取/查询资源信息,在浏览器中直接输入url+请求参数点击enter之后连接成功服务器就能获取到的内容,post请求一般用于更新 ...

  2. 发送http请求和https请求的工具类

    package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...

  3. haproxy 中的http请求和https请求

    use Mojolicious::Lite; use JSON qw/encode_json decode_json/; use Encode; no strict; use JSON; # /foo ...

  4. 使用SoapUI工具做get请求和post请求接口测试

    祝大家节日快乐啦. 之前写过的一篇帖子已经介绍了SoapUI工具的基本使用,所以在此不再重复讲解关于建工程.建测试套件.添加用例等操作,可查看该篇文章详解:http://www.cnblogs.com ...

  5. SoapUI工具做get请求和post请求接口测试

    转载自:https://www.cnblogs.com/hong-fithing/p/7617366.html 此篇主要介绍SoapUI工具做常用的两种请求接口测试,分别是get请求和post请求. ...

  6. 浅说Get请求和Post请求

    Web 上最常用的两种 Http 请求就是 Get 请求和 Post 请求了.我们在做 java web 开发时,也总会在 servlet 中通过 doGet 和 doPost 方法来处理请求:更经常 ...

  7. HttpClient之Get请求和Post请求示例

    HttpClient之Get请求和Post请求示例 博客分类: Java综合   HttpClient的支持在HTTP/1.1规范中定义的所有的HTTP方法:GET, HEAD, POST, PUT, ...

  8. GET 请求和 POST 请求的区别和使用

    作为前端开发, HTTP 中的 POST 请求和 GET 请求是经常会用到的东西,有的人可能知道,但对其原理和如何使用并不特别清楚,那么今天来浅谈一下两者的区别与如何使用. GET请求和POST请求的 ...

  9. 03_Django-GET请求和POST请求-设计模式及模板层

    03_Django-GET请求和POST请求-设计模式及模板层 视频:https://www.bilibili.com/video/BV1vK4y1o7jH 博客:https://blog.csdn. ...

随机推荐

  1. loj2395 [JOISC 2017 Day 2]火车旅行

    传送门 分析 我们知道无论往左走还是往右走一定都是往不低于这个点的地方走 于是我们可以考虑用倍增来维护一个点向左和向右走$2^i$最远分别能走到哪里 我们可以先用单调栈求出直走一步的情况,之后再处理倍 ...

  2. ZROI2018提高day3t2

    传送门 分析 我们设A[i]表示点i有几个矿,B[i]表示这之中有几个矿是第一次出现,所以点i的贡献即为 (2^B[i]-1)*(2^(A[i]-B[i])) 注意减一的原因是第一次出现的矿应至少有一 ...

  3. tab下拉菜单

    这个想法早就有的 (写tab下拉菜单)就觉得自己对js不是很熟   所以一直没有写 花了不少时间 <!DOCTYPE html> <html> <head> < ...

  4. 优先队列详解priority_queue .RP

    ) 删除.在最小优先队列(min priorityq u e u e)中,查找操作用来搜索优先权最小的元素,删除操作用来删除该元素;对于最大优先队列(max priority queue),查找操作用 ...

  5. clions的使用

    最近无聊玩了下CLion这个IDE,顺便学习了下CMAKE怎么使用.话说CLion的CMAKE的支持还不是特别的完好,和命令行模式还有有区别,有如下几个问题: 1:CMAKE的编译目录不能指定,而是I ...

  6. 数据结构_sfdg(小F打怪)

    问题描述 小 F 很爱打怪, 今天因为系统 bug, 他提前得知了 n 只怪的出现顺序以及击倒每只怪得到的成就值 ai. 设第一只怪出现的时间为第 1 秒,这个游戏每过 1 秒钟出现一只新怪且没被击倒 ...

  7. GTXE_COMMON

    http://forums.xilinx.com/xlnx/board/crawl_message?board.id=IMPBD&message.id=9657 If you are usin ...

  8. linux手动安装配置mysql5.6

    1.准备工作 ①官网下载:https://dev.mysql.com/downloads/mysql/5.6.html#downloads 下载之后上传到服务器. ②创建linux组用户 groupa ...

  9. spark(2.1) - spark-shell 下文件系统的数据读写

    spark-shell 本地文件系统数据读写 [ file:// ] 读取 :sc.textFile (" ****") 写入:saveAsTextFile ("**** ...

  10. KDevelop4调试pcl一直读取不到.pcd文件

    如题所示,KD下,能编译,运行时一直使用reader.read读取不到pcd,但是使用cmake能正常运行. 后来,使用terminator删掉工程的build文件夹,直接在工程文件下进行编译,报错提 ...