【Java工具七】java使用HttpClient的post请求http、https示例

古城微笑少年丶 2022-05-18 09:04 461阅读 0赞
  1. package com.xxx.utils;
  2. import com.google.gson.Gson;
  3. import org.apache.commons.codec.binary.Base64;
  4. import org.apache.commons.httpclient.HttpClient;
  5. import org.apache.commons.httpclient.HttpException;
  6. import org.apache.commons.httpclient.NameValuePair;
  7. import org.apache.commons.httpclient.methods.PostMethod;
  8. import org.apache.http.client.config.RequestConfig;
  9. import org.apache.http.config.ConnectionConfig;
  10. import org.apache.http.config.SocketConfig;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
  13. import org.apache.http.impl.client.HttpClientBuilder;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import javax.net.ssl.HttpsURLConnection;
  18. import javax.net.ssl.SSLContext;
  19. import javax.net.ssl.TrustManager;
  20. import javax.net.ssl.X509TrustManager;
  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.net.HttpURLConnection;
  26. import java.net.URL;
  27. import java.net.URLConnection;
  28. import java.net.URLEncoder;
  29. import java.nio.charset.Charset;
  30. import java.security.cert.X509Certificate;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. /**
  34. * http 请求接口
  35. *
  36. *
  37. */
  38. public class HttpUtils {
  39. public static final Gson gson = new Gson();
  40. private static final String HTTP_PREFIX = "http://";
  41. private static final String HTTPS_PREFIX = "https://";
  42. private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
  43. /**
  44. * 请求超时时间
  45. */
  46. public static final int CONNECTION_TIMEOUT_DEFAULT = 30000;
  47. /**
  48. * 响应超时时间
  49. */
  50. public static final int SOCKET_TIMEOUT_DEFAULT = 50000;
  51. /**
  52. * 无限超时时间
  53. */
  54. public static final int INFINITE_TIMEOUT = 0;
  55. /**
  56. * 接收/传输数据时使用的默认socket缓冲字节大小
  57. */
  58. public static final int SOCKET_BUFFER_SIZE_DEFAULT = 81920;
  59. /**
  60. * 请求失败后重新尝试的次数
  61. */
  62. public static final int RETRY_COUNT_DEFAULT = 2;
  63. /**
  64. * 默认字符集
  65. */
  66. public static final String DEFAULT_CHARSET = "UTF-8";
  67. public static final CloseableHttpClient httpClient = buildHttpClient(SOCKET_TIMEOUT_DEFAULT);
  68. public static final CloseableHttpClient httpClientNoTimeout = buildHttpClient(INFINITE_TIMEOUT);
  69. private static CloseableHttpClient buildHttpClient(int socketTimeout) {
  70. // 设置最大连接数和每个host的最大连接数
  71. HttpClientBuilder httpClientBuilder = HttpClients.custom().setMaxConnTotal(2000).setMaxConnPerRoute(2000);
  72. // 内部默认使用 PoolingHttpClientConnectionManager 作为其连接管理器, 再次设置会覆盖下面其它参数的设置
  73. // httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
  74. // 设置服务器连接超时时间 及 服务器响应超时时间
  75. httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT_DEFAULT).setSocketTimeout(socketTimeout).build());
  76. // 设置在关闭TCP连接时最大停留时间,是否禁用优化算法延迟发送数据 及 在非阻塞I/O情况下的服务器响应时间
  77. httpClientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoLinger(1500).setTcpNoDelay(true).setSoTimeout(socketTimeout).build());
  78. // 设置接收/传输数据时的buffer大小,及默认字符集
  79. httpClientBuilder.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(SOCKET_BUFFER_SIZE_DEFAULT).setCharset(Charset.forName(DEFAULT_CHARSET)).build());
  80. // 设置失败后重新尝试访问的处理器,不使用已经请求的连接
  81. httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT_DEFAULT, false));
  82. return httpClientBuilder.build();
  83. }
  84. private static TrustManager myX509TrustManager = new X509TrustManager() {
  85. @Override
  86. public void checkClientTrusted(X509Certificate[] arg0, String arg1)
  87. throws java.security.cert.CertificateException {
  88. // TODO Auto-generated method stub
  89. }
  90. @Override
  91. public void checkServerTrusted(X509Certificate[] arg0, String arg1)
  92. throws java.security.cert.CertificateException {
  93. // TODO Auto-generated method stub
  94. }
  95. @Override
  96. public X509Certificate[] getAcceptedIssuers() {
  97. // TODO Auto-generated method stub
  98. return null;
  99. }
  100. };
  101. public static byte[] readInputStream(InputStream inStream) throws Exception {
  102. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  103. byte[] buffer = new byte[1024];
  104. int len = 0;
  105. while ((len = inStream.read(buffer)) != -1) {
  106. outStream.write(buffer, 0, len);
  107. }
  108. byte[] data = outStream.toByteArray();// 网页的二进制数据
  109. outStream.close();
  110. inStream.close();
  111. return data;
  112. }
  113. public static String getPostParam(Map<String, Object> params) throws Exception {
  114. StringBuffer buffer = new StringBuffer();
  115. for (String key : params.keySet()) {
  116. String urlKey = URLEncoder.encode(key, "UTF-8");
  117. String urlValue = URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8");
  118. buffer.append(urlKey).append("=").append(urlValue).append("&");
  119. }
  120. String paramStr = buffer.toString();
  121. if (paramStr.endsWith("&") && paramStr.length() > 0) {
  122. paramStr = paramStr.substring(0, paramStr.length() - 1);
  123. }
  124. return paramStr;
  125. }
  126. public static String postForm(String url, Map<String, Object> params) throws Exception {
  127. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(params));
  128. OutputStream out = null;
  129. if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) {
  130. url = HTTP_PREFIX + url;
  131. }
  132. URL localURL = new URL(url);
  133. URLConnection connection =null;
  134. if(url.toLowerCase().startsWith(HTTPS_PREFIX)){
  135. SSLContext sslcontext = SSLContext.getInstance("TLS");
  136. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  137. URL requestUrl = new URL(url);
  138. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  139. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  140. connection=httpsConn;
  141. }else{
  142. connection = (HttpURLConnection) localURL.openConnection();
  143. }
  144. connection.setRequestProperty("accept", "*/*");
  145. connection.setRequestProperty("connection", "Keep-Alive");
  146. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  147. connection.setDoOutput(true);
  148. connection.setDoInput(true);
  149. out = connection.getOutputStream();
  150. out.write(getPostParam(params).getBytes());
  151. out.flush();
  152. InputStream inStream = connection.getInputStream();
  153. String str = new String(readInputStream(inStream), "UTF-8");
  154. return str;
  155. }
  156. public static String postHttps(String url, String params) throws Exception {
  157. LOGGER.info("请求的url {},输入参数 {}", url, new Gson().toJson(params));
  158. OutputStream out = null;
  159. if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) {
  160. url = HTTP_PREFIX + url;
  161. }
  162. URL localURL = new URL(url);
  163. URLConnection connection =null;
  164. if(url.toLowerCase().startsWith(HTTPS_PREFIX)){
  165. SSLContext sslcontext = SSLContext.getInstance("TLS");
  166. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  167. URL requestUrl = new URL(url);
  168. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  169. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  170. connection=httpsConn;
  171. }else{
  172. connection = (HttpURLConnection) localURL.openConnection();
  173. }
  174. connection.setRequestProperty("accept", "*/*");
  175. connection.setRequestProperty("connection", "Keep-Alive");
  176. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  177. connection.setDoOutput(true);
  178. connection.setDoInput(true);
  179. out = connection.getOutputStream();
  180. out.write(params.getBytes());
  181. out.flush();
  182. InputStream inStream = connection.getInputStream();
  183. String str = new String(readInputStream(inStream), "UTF-8");
  184. return str;
  185. }
  186. public static String postForm(String url, String params) throws Exception {
  187. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(params));
  188. OutputStream out = null;
  189. if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) {
  190. url = HTTP_PREFIX + url;
  191. }
  192. URL localURL = new URL(url);
  193. HttpURLConnection connection = (HttpURLConnection) localURL.openConnection();
  194. connection.setRequestProperty("accept", "*/*");
  195. connection.setRequestProperty("connection", "Keep-Alive");
  196. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  197. connection.setDoOutput(true);
  198. connection.setDoInput(true);
  199. out = connection.getOutputStream();
  200. out.write(params.getBytes());
  201. out.flush();
  202. InputStream inStream = connection.getInputStream();
  203. String str = new String(readInputStream(inStream), "UTF-8");
  204. // String str = "";
  205. return str;
  206. }
  207. public static String postGsonForm(String url, String params) throws Exception {
  208. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(params));
  209. OutputStream out = null;
  210. URL localURL = new URL(url);
  211. HttpURLConnection connection = null;
  212. if(url.toLowerCase().startsWith(HTTPS_PREFIX)){
  213. SSLContext sslcontext = SSLContext.getInstance("TLS");
  214. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  215. URL requestUrl = new URL(url);
  216. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  217. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  218. connection=httpsConn;
  219. }else{
  220. connection = (HttpURLConnection) localURL.openConnection();
  221. }
  222. connection.setRequestProperty("Accept", "*/*");
  223. connection.setRequestProperty("connection", "Keep-Alive");
  224. connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  225. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  226. connection.setDoOutput(true);
  227. connection.setDoInput(true);
  228. out = connection.getOutputStream();
  229. out.write(params.getBytes("UTF-8"));
  230. out.flush();
  231. InputStream inStream = connection.getInputStream();
  232. String str = new String(readInputStream(inStream), "UTF-8");
  233. return str;
  234. }
  235. public static String postGsonFormForHeader
  236. (String url,String params,String accesstoken,String orgId,String appId) throws Exception {
  237. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(params));
  238. OutputStream out = null;
  239. URL localURL = new URL(url);
  240. HttpURLConnection connection = null;
  241. if(url.toLowerCase().startsWith(HTTPS_PREFIX)){
  242. SSLContext sslcontext = SSLContext.getInstance("TLS");
  243. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  244. URL requestUrl = new URL(url);
  245. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  246. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  247. connection=httpsConn;
  248. }else{
  249. connection = (HttpURLConnection) localURL.openConnection();
  250. }
  251. connection.setRequestProperty("Accept", "*/*");
  252. connection.setRequestProperty("connection", "Keep-Alive");
  253. connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  254. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  255. connection.setRequestProperty(accesstoken, accesstoken);
  256. connection.setRequestProperty(orgId, orgId);
  257. connection.setRequestProperty(appId, appId);
  258. connection.setDoOutput(true);
  259. connection.setDoInput(true);
  260. out = connection.getOutputStream();
  261. out.write(params.getBytes("UTF-8"));
  262. out.flush();
  263. InputStream inStream = connection.getInputStream();
  264. String str = new String(readInputStream(inStream), "UTF-8");
  265. return str;
  266. }
  267. public static String postGsonForm(String url, String params, Map<String, Object> headerParams) throws Exception {
  268. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(params));
  269. OutputStream out = null;
  270. URL localURL = new URL(url);
  271. HttpURLConnection connection = null;
  272. if(url.toLowerCase().startsWith(HTTPS_PREFIX)){
  273. SSLContext sslcontext = SSLContext.getInstance("TLS");
  274. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  275. URL requestUrl = new URL(url);
  276. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  277. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  278. connection=httpsConn;
  279. }else{
  280. connection = (HttpURLConnection) localURL.openConnection();
  281. }
  282. connection.setRequestProperty("Accept", "*/*");
  283. connection.setRequestProperty("connection", "Keep-Alive");
  284. connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  285. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  286. connection.setDoOutput(true);
  287. connection.setDoInput(true);
  288. if (headerParams != null && !headerParams.isEmpty()) {
  289. for(Map.Entry<String, Object> headerParam:headerParams.entrySet()){
  290. connection.setRequestProperty(headerParam.getKey(), headerParam.getValue().toString());
  291. }
  292. }
  293. out = connection.getOutputStream();
  294. out.write(params.getBytes("UTF-8"));
  295. out.flush();
  296. InputStream inStream = connection.getInputStream();
  297. String str = new String(readInputStream(inStream), "UTF-8");
  298. return str;
  299. }
  300. public static String getForm(String url, String params) throws Exception {
  301. url = url + "?" + params;
  302. URL localURL = new URL(url);
  303. HttpURLConnection connection = null;
  304. if(url.startsWith(HTTPS_PREFIX)){
  305. SSLContext sslcontext = SSLContext.getInstance("TLS");
  306. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  307. URL requestUrl = new URL(url);
  308. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  309. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  310. connection=httpsConn;
  311. }else{
  312. connection = (HttpURLConnection) localURL.openConnection();
  313. }
  314. connection.setRequestProperty("accept", "*/*");
  315. connection.setRequestProperty("connection", "Keep-Alive");
  316. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  317. InputStream inStream = connection.getInputStream();
  318. String str = new String(readInputStream(inStream), "UTF-8");
  319. return str;
  320. }
  321. public static String getForm(String url, Map<String, Object> params) throws Exception {
  322. url = url + "?" + getPostParam(params);
  323. URL localURL = new URL(url);
  324. HttpURLConnection connection = null;
  325. if(url.startsWith(HTTPS_PREFIX)){
  326. SSLContext sslcontext = SSLContext.getInstance("TLS");
  327. sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
  328. URL requestUrl = new URL(url);
  329. HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
  330. httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
  331. connection=httpsConn;
  332. }else{
  333. connection = (HttpURLConnection) localURL.openConnection();
  334. }
  335. connection.setRequestProperty("accept", "*/*");
  336. connection.setRequestProperty("connection", "Keep-Alive");
  337. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  338. connection.setUseCaches(false);
  339. InputStream inStream = connection.getInputStream();
  340. String str = new String(readInputStream(inStream), "UTF-8");
  341. return str;
  342. }
  343. public static Map<String, Object> getMap(String key, Object value) {
  344. Map<String, Object> result = new HashMap<String, Object>();
  345. result.put(key, value);
  346. return result;
  347. }
  348. public static String post(String url, NameValuePair[] data) {
  349. LOGGER.info("请求的url {},输入参数{}", url, new Gson().toJson(data));
  350. String responseMsg = null;
  351. // 1.构造HttpClient的实例
  352. HttpClient httpClient = new HttpClient();
  353. httpClient.getParams().setContentCharset("UTF-8");
  354. // 2.构造PostMethod的实例
  355. PostMethod postMethod = new PostMethod(url);
  356. // 3.把参数值放入到PostMethod对象中
  357. postMethod.setRequestBody(data);
  358. try {
  359. // 4.执行postMethod,调用http接口
  360. httpClient.executeMethod(postMethod);// 200
  361. // 5.读取内容
  362. responseMsg = postMethod.getResponseBodyAsString().trim();
  363. // 6.处理返回的内容
  364. } catch (HttpException e) {
  365. LOGGER.error(e.getMessage(),e);
  366. } catch (IOException e) {
  367. LOGGER.error(e.getMessage(),e);
  368. } finally {
  369. // 7.释放连接
  370. postMethod.releaseConnection();
  371. }
  372. return responseMsg;
  373. }
  374. public static void main(String[] args) {
  375. try {
  376. Map<String, Object> paramsMap = new HashMap<>();
  377. paramsMap.put("orgId", "5835");
  378. String[] userIds = {"84544"};
  379. paramsMap.put("userIds", userIds);
  380. String[] userNames = {"测试名片2"};
  381. paramsMap.put("userNames", userNames);
  382. String[] userPhones = {"18611368266"};
  383. paramsMap.put("userPhones", userPhones);
  384. Map<String, Object> headerParams = new HashMap<>();
  385. headerParams.put("token", "4b55b10a8f454beacf8d9fd9b85f453a");
  386. String params = JSONUtils.toJson(paramsMap);
  387. String url = "http://172.31.81.37:8080/CardManagerUI/usermanager/grantUserCard";
  388. String rv = HttpUtils.postGsonForm(url, params,headerParams);
  389. System.out.println("rv:"+rv);
  390. }
  391. catch (Exception e) {
  392. e.printStackTrace();
  393. }
  394. }
  395. }

下面是个人创建的公众号,主攻Java方向,有兴趣的可以扫描二维码。

  1. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1Zm9yZXZlcmxvdmU_size_16_color_FFFFFF_t_70][]

发表评论

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

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

相关阅读