Java实现HttpClient发送GET、POST请求(https、http)

朴灿烈づ我的快乐病毒、 2021-09-28 22:06 1643阅读 0赞

1、引入相关依赖包

jar包下载:httpcore4.5.5.jar fastjson-1.2.47.jar

maven:

复制代码

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.5</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.47</version>
  10. </dependency>

复制代码

2、主要类HttpClientService

复制代码

  1. 1 package com.sinotn.service;
  2. 2
  3. 3 import com.alibaba.fastjson.JSONObject;
  4. 4 import org.apache.http.HttpEntity;
  5. 5 import org.apache.http.NameValuePair;
  6. 6 import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. 7 import org.apache.http.client.methods.CloseableHttpResponse;
  8. 8 import org.apache.http.client.methods.HttpGet;
  9. 9 import org.apache.http.client.methods.HttpPost;
  10. 10 import org.apache.http.client.utils.URIBuilder;
  11. 11 import org.apache.http.entity.StringEntity;
  12. 12 import org.apache.http.impl.client.CloseableHttpClient;
  13. 13 import org.apache.http.impl.client.HttpClients;
  14. 14 import org.apache.http.message.BasicHeader;
  15. 15 import org.apache.http.message.BasicNameValuePair;
  16. 16 import org.apache.http.util.EntityUtils;
  17. 17 import org.slf4j.Logger;
  18. 18 import org.slf4j.LoggerFactory;
  19. 19 import java.util.ArrayList;
  20. 20 import java.util.List;
  21. 21
  22. 22 /**
  23. 23 * HttpClient发送GET、POST请求
  24. 24 * @Author libin
  25. 25 * @CreateDate 2018.5.28 16:56
  26. 26 */
  27. 27 public class HttpClientService {
  28. 28
  29. 29 private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
  30. 30 /**
  31. 31 * 返回成功状态码
  32. 32 */
  33. 33 private static final int SUCCESS_CODE = 200;
  34. 34
  35. 35 /**
  36. 36 * 发送GET请求
  37. 37 * @param url 请求url
  38. 38 * @param nameValuePairList 请求参数
  39. 39 * @return JSON或者字符串
  40. 40 * @throws Exception
  41. 41 */
  42. 42 public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{
  43. 43 JSONObject jsonObject = null;
  44. 44 CloseableHttpClient client = null;
  45. 45 CloseableHttpResponse response = null;
  46. 46 try{
  47. 47 /**
  48. 48 * 创建HttpClient对象
  49. 49 */
  50. 50 client = HttpClients.createDefault();
  51. 51 /**
  52. 52 * 创建URIBuilder
  53. 53 */
  54. 54 URIBuilder uriBuilder = new URIBuilder(url);
  55. 55 /**
  56. 56 * 设置参数
  57. 57 */
  58. 58 uriBuilder.addParameters(nameValuePairList);
  59. 59 /**
  60. 60 * 创建HttpGet
  61. 61 */
  62. 62 HttpGet httpGet = new HttpGet(uriBuilder.build());
  63. 63 /**
  64. 64 * 设置请求头部编码
  65. 65 */
  66. 66 httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
  67. 67 /**
  68. 68 * 设置返回编码
  69. 69 */
  70. 70 httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
  71. 71 /**
  72. 72 * 请求服务
  73. 73 */
  74. 74 response = client.execute(httpGet);
  75. 75 /**
  76. 76 * 获取响应吗
  77. 77 */
  78. 78 int statusCode = response.getStatusLine().getStatusCode();
  79. 79
  80. 80 if (SUCCESS_CODE == statusCode){
  81. 81 /**
  82. 82 * 获取返回对象
  83. 83 */
  84. 84 HttpEntity entity = response.getEntity();
  85. 85 /**
  86. 86 * 通过EntityUitls获取返回内容
  87. 87 */
  88. 88 String result = EntityUtils.toString(entity,"UTF-8");
  89. 89 /**
  90. 90 * 转换成json,根据合法性返回json或者字符串
  91. 91 */
  92. 92 try{
  93. 93 jsonObject = JSONObject.parseObject(result);
  94. 94 return jsonObject;
  95. 95 }catch (Exception e){
  96. 96 return result;
  97. 97 }
  98. 98 }else{
  99. 99 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");
  100. 100 }
  101. 101 }catch (Exception e){
  102. 102 LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
  103. 103 } finally {
  104. 104 response.close();
  105. 105 client.close();
  106. 106 }
  107. 107 return null;
  108. 108 }
  109. 109
  110. 110 /**
  111. 111 * 发送POST请求
  112. 112 * @param url
  113. 113 * @param nameValuePairList
  114. 114 * @return JSON或者字符串
  115. 115 * @throws Exception
  116. 116 */
  117. 117 public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{
  118. 118 JSONObject jsonObject = null;
  119. 119 CloseableHttpClient client = null;
  120. 120 CloseableHttpResponse response = null;
  121. 121 try{
  122. 122 /**
  123. 123 * 创建一个httpclient对象
  124. 124 */
  125. 125 client = HttpClients.createDefault();
  126. 126 /**
  127. 127 * 创建一个post对象
  128. 128 */
  129. 129 HttpPost post = new HttpPost(url);
  130. 130 /**
  131. 131 * 包装成一个Entity对象
  132. 132 */
  133. 133 StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
  134. 134 /**
  135. 135 * 设置请求的内容
  136. 136 */
  137. 137 post.setEntity(entity);
  138. 138 /**
  139. 139 * 设置请求的报文头部的编码
  140. 140 */
  141. 141 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
  142. 142 /**
  143. 143 * 设置请求的报文头部的编码
  144. 144 */
  145. 145 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
  146. 146 /**
  147. 147 * 执行post请求
  148. 148 */
  149. 149 response = client.execute(post);
  150. 150 /**
  151. 151 * 获取响应码
  152. 152 */
  153. 153 int statusCode = response.getStatusLine().getStatusCode();
  154. 154 if (SUCCESS_CODE == statusCode){
  155. 155 /**
  156. 156 * 通过EntityUitls获取返回内容
  157. 157 */
  158. 158 String result = EntityUtils.toString(response.getEntity(),"UTF-8");
  159. 159 /**
  160. 160 * 转换成json,根据合法性返回json或者字符串
  161. 161 */
  162. 162 try{
  163. 163 jsonObject = JSONObject.parseObject(result);
  164. 164 return jsonObject;
  165. 165 }catch (Exception e){
  166. 166 return result;
  167. 167 }
  168. 168 }else{
  169. 169 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
  170. 170 }
  171. 171 }catch (Exception e){
  172. 172 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
  173. 173 }finally {
  174. 174 response.close();
  175. 175 client.close();
  176. 176 }
  177. 177 return null;
  178. 178 }
  179. 179
  180. 180 /**
  181. 181 * 组织请求参数{参数名和参数值下标保持一致}
  182. 182 * @param params 参数名数组
  183. 183 * @param values 参数值数组
  184. 184 * @return 参数对象
  185. 185 */
  186. 186 public static List<NameValuePair> getParams(Object[] params, Object[] values){
  187. 187 /**
  188. 188 * 校验参数合法性
  189. 189 */
  190. 190 boolean flag = params.length>0 && values.length>0 && params.length == values.length;
  191. 191 if (flag){
  192. 192 List<NameValuePair> nameValuePairList = new ArrayList<>();
  193. 193 for(int i =0; i<params.length; i++){
  194. 194 nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString()));
  195. 195 }
  196. 196 return nameValuePairList;
  197. 197 }else{
  198. 198 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不一致");
  199. 199 }
  200. 200 return null;
  201. 201 }
  202. 202 }

复制代码

3、调用方法

复制代码

  1. 1 package com.sinotn.service.impl;
  2. 2
  3. 3 import com.sinotn.service.HttpClientService;
  4. 4 import org.apache.http.NameValuePair;
  5. 5
  6. 6 import java.util.List;
  7. 7
  8. 8 /**
  9. 9 * 发送post/get 测试类
  10. 10 */
  11. 11 public class Test {
  12. 12
  13. 13 public static void main(String[] args) throws Exception{
  14. 14 String url = "要请求的url地址";
  15. 15 /**
  16. 16 * 参数值
  17. 17 */
  18. 18 Object [] params = new Object[]{"param1","param2"};
  19. 19 /**
  20. 20 * 参数名
  21. 21 */
  22. 22 Object [] values = new Object[]{"value1","value2"};
  23. 23 /**
  24. 24 * 获取参数对象
  25. 25 */
  26. 26 List<NameValuePair> paramsList = HttpClientService.getParams(params, values);
  27. 27 /**
  28. 28 * 发送get
  29. 29 */
  30. 30 Object result = HttpClientService.sendGet(url, paramsList);
  31. 31 /**
  32. 32 * 发送post
  33. 33 */
  34. 34 Object result2 = HttpClientService.sendPost(url, paramsList);
  35. 35
  36. 36 System.out.println("GET返回信息:" + result);
  37. 37 System.out.println("POST返回信息:" + result2);
  38. 38 }
  39. 39 }

复制代码

4、对于发送https

为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。

写一个SSLClient类,继承至HttpClient

复制代码

  1. 1 import java.security.cert.CertificateException;
  2. 2 import java.security.cert.X509Certificate;
  3. 3 import javax.net.ssl.SSLContext;
  4. 4 import javax.net.ssl.TrustManager;
  5. 5 import javax.net.ssl.X509TrustManager;
  6. 6 import org.apache.http.conn.ClientConnectionManager;
  7. 7 import org.apache.http.conn.scheme.Scheme;
  8. 8 import org.apache.http.conn.scheme.SchemeRegistry;
  9. 9 import org.apache.http.conn.ssl.SSLSocketFactory;
  10. 10 import org.apache.http.impl.client.DefaultHttpClient;
  11. 11 //用于进行Https请求的HttpClient
  12. 12 public class SSLClient extends DefaultHttpClient{
  13. 13 public SSLClient() throws Exception{
  14. 14 super();
  15. 15 SSLContext ctx = SSLContext.getInstance("TLS");
  16. 16 X509TrustManager tm = new X509TrustManager() {
  17. 17 @Override
  18. 18 public void checkClientTrusted(X509Certificate[] chain,
  19. 19 String authType) throws CertificateException {
  20. 20 }
  21. 21 @Override
  22. 22 public void checkServerTrusted(X509Certificate[] chain,
  23. 23 String authType) throws CertificateException {
  24. 24 }
  25. 25 @Override
  26. 26 public X509Certificate[] getAcceptedIssuers() {
  27. 27 return null;
  28. 28 }
  29. 29 };
  30. 30 ctx.init(null, new TrustManager[]{tm}, null);
  31. 31 SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  32. 32 ClientConnectionManager ccm = this.getConnectionManager();
  33. 33 SchemeRegistry sr = ccm.getSchemeRegistry();
  34. 34 sr.register(new Scheme("https", 443, ssf));
  35. 35 }
  36. 36 }

复制代码

5、对于https调用

1165001-20180601134234180-703438592.png

转载自:https://www.cnblogs.com/klslb/p/9121276.html

发表评论

表情:
评论列表 (有 0 条评论,1643人围观)

还没有评论,来说两句吧...

相关阅读