今天在搭建公司項目框架的時候,發現缺乏了一個Java發送HTTP請求的工具類,在網上找了一通,通過本身的改造,已經能實現get請求和post請求的了,如今將代碼貼在這裏。給你們參考。html
1 package com.sunyard.util; 2 3 import com.sunyard.constans.Constants; 4 5 import org.apache.commons.httpclient.*; 6 import org.apache.commons.httpclient.methods.GetMethod; 7 import org.apache.commons.httpclient.methods.PostMethod; 8 import org.apache.commons.httpclient.methods.RequestEntity; 9 import org.apache.commons.httpclient.methods.StringRequestEntity; 10 import org.apache.commons.httpclient.params.HttpConnectionManagerParams; 11 import org.apache.commons.lang.StringUtils; 12 import org.apache.logging.log4j.LogManager; 13 import org.apache.logging.log4j.Logger; 14 15 import java.io.IOException; 16 import java.net.URL; 17 18 public class HTTPUtils { 19 20 private final static Logger logger = LogManager.getLogger(Constants.LOGNAME); 21 22 private final static String OPERATER_NAME = "【HTTP操做】"; 23 24 private final static int SUCCESS = 200; 25 26 private final static String UTF8 = "UTF-8"; 27 28 private HttpClient client; 29 30 private static HTTPUtils instance = new HTTPUtils(); 31 32 /** 33 * 私有化構造器 34 */ 35 private HTTPUtils() { 36 37 HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); 38 HttpConnectionManagerParams params = httpConnectionManager.getParams(); 39 params.setConnectionTimeout(5000); 40 params.setSoTimeout(20000); 41 params.setDefaultMaxConnectionsPerHost(1000); 42 params.setMaxTotalConnections(1000); 43 client = new HttpClient(httpConnectionManager); 44 client.getParams().setContentCharset(UTF8); 45 client.getParams().setHttpElementCharset(UTF8); 46 } 47 48 /** 49 * get請求 50 */ 51 public static String get(URL url) { 52 return instance.doGet(url); 53 } 54 55 private String doGet(URL url) { 56 long beginTime = System.currentTimeMillis(); 57 String respStr = StringUtils.EMPTY; 58 try { 59 logger.info(OPERATER_NAME + "開始get通訊,目標host:" + url); 60 HttpMethod method = new GetMethod(url.toString()); 61 // 中文轉碼 62 method.getParams().setContentCharset(UTF8); 63 try { 64 client.executeMethod(method); 65 } catch (HttpException e) { 66 67 logger.error(new StringBuffer("發送HTTP GET給\r\n").append(url) 68 .append("\r\nHTTP異常\r\n"), e); 69 } catch (IOException e) { 70 71 logger.error(new StringBuffer("發送HTTP GET給\r\n").append(url) 72 .append("\r\nIO異常\r\n"), e); 73 } 74 if (method.getStatusCode() == SUCCESS) { 75 respStr = method.getResponseBodyAsString(); 76 } 77 // 釋放鏈接 78 method.releaseConnection(); 79 80 logger.info(OPERATER_NAME + "通信完成,返回碼:" + method.getStatusCode()); 81 logger.info(OPERATER_NAME + "返回內容:" + method.getResponseBodyAsString()); 82 logger.info(OPERATER_NAME + "結束..返回結果:" + respStr); 83 } catch (Exception e) { 84 logger.info(OPERATER_NAME, e); 85 } 86 long endTime = System.currentTimeMillis(); 87 logger.info(OPERATER_NAME + "共計耗時:" + (endTime - beginTime) + "ms"); 88 89 return respStr; 90 } 91 92 93 /** 94 * POST請求 95 */ 96 public static String post(URL url, String content) { 97 return instance.doPost(url, content); 98 } 99 100 private String doPost(URL url, String content) { 101 long beginTime = System.currentTimeMillis(); 102 String respStr = StringUtils.EMPTY; 103 try { 104 logger.info(OPERATER_NAME + "開始post通訊,目標host:" + url.toString()); 105 logger.info("通訊內容:" + content); 106 PostMethod post = new PostMethod(url.toString()); 107 RequestEntity requestEntity = new StringRequestEntity(content, "application/json;charse=UTF-8", UTF8); 108 post.setRequestEntity(requestEntity); 109 // 設置格式 110 post.getParams().setContentCharset(UTF8); 111 112 client.executeMethod(post); 113 if (post.getStatusCode() == SUCCESS) { 114 respStr = post.getResponseBodyAsString(); 115 } 116 117 logger.info(OPERATER_NAME + "通信完成,返回碼:" + post.getStatusCode()); 118 logger.info(OPERATER_NAME + "返回內容:" + post.getResponseBodyAsString()); 119 logger.info(OPERATER_NAME + "結束..返回結果:" + respStr); 120 post.releaseConnection(); 121 122 } catch (Exception e) { 123 logger.error(OPERATER_NAME, e); 124 } 125 long endTime = System.currentTimeMillis(); 126 logger.info(OPERATER_NAME + "共計耗時:" + (endTime - beginTime) + "ms"); 127 return respStr; 128 } 129 130 }
jar依賴如圖java
編寫測試類測試:apache
1 public static void main(String[] args) throws Exception { 2 JSONObject json = new JSONObject(); 3 json.put("action", "test"); 4 URL url = new URL("http://localhost:8080/TPSServer/door.do"); 5 String resp = post(url, json.toString()); 6 System.out.println(resp); 7 }
控制檯輸出結果:json
1 2017-07-26 11:17:09 GMT+08:00 INFO com.sunyard.util.HTTPUtils 106 doPost - 【HTTP操做】開始post通訊,目標host:http://localhost:8080/TPSServer/door.do 2 2017-07-26 11:17:09 GMT+08:00 INFO com.sunyard.util.HTTPUtils 107 doPost - 通訊內容:{"action":"test"} 3 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 119 doPost - 【HTTP操做】通信完成,返回碼:200 4 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 120 doPost - 【HTTP操做】返回內容:{"errorcode":"0","errormsg":"success"} 5 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 121 doPost - 【HTTP操做】結束..返回結果:{"errorcode":"0","errormsg":"success"} 6 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 128 doPost - 【HTTP操做】共計耗時:579ms 7 {"errorcode":"0","errormsg":"success"}
HttpClient工具包的使用,請你們參考。app
from: https://www.cnblogs.com/yujiwei/p/7238613.html框架