jar包下載:httpcore4.5.5.jar fastjson-1.2.47.jarjava
maven:apache
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
1 package com.sinotn.service; 2
3 import com.alibaba.fastjson.JSONObject; 4 import org.apache.http.HttpEntity; 5 import org.apache.http.NameValuePair; 6 import org.apache.http.client.entity.UrlEncodedFormEntity; 7 import org.apache.http.client.methods.CloseableHttpResponse; 8 import org.apache.http.client.methods.HttpGet; 9 import org.apache.http.client.methods.HttpPost; 10 import org.apache.http.client.utils.URIBuilder; 11 import org.apache.http.entity.StringEntity; 12 import org.apache.http.impl.client.CloseableHttpClient; 13 import org.apache.http.impl.client.HttpClients; 14 import org.apache.http.message.BasicHeader; 15 import org.apache.http.message.BasicNameValuePair; 16 import org.apache.http.util.EntityUtils; 17 import org.slf4j.Logger; 18 import org.slf4j.LoggerFactory; 19 import java.util.ArrayList; 20 import java.util.List; 21
22 /**
23 * HttpClient發送GET、POST請求 24 * @Author libin 25 * @CreateDate 2018.5.28 16:56 26 */
27 public class HttpClientService { 28
29 private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class); 30 /**
31 * 返回成功狀態碼 32 */
33 private static final int SUCCESS_CODE = 200; 34
35 /**
36 * 發送GET請求 37 * @param url 請求url 38 * @param nameValuePairList 請求參數 39 * @return JSON或者字符串 40 * @throws Exception 41 */
42 public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{ 43 JSONObject jsonObject = null; 44 CloseableHttpClient client = null; 45 CloseableHttpResponse response = null; 46 try{ 47 /**
48 * 建立HttpClient對象 49 */
50 client = HttpClients.createDefault(); 51 /**
52 * 建立URIBuilder 53 */
54 URIBuilder uriBuilder = new URIBuilder(url); 55 /**
56 * 設置參數 57 */
58 uriBuilder.addParameters(nameValuePairList); 59 /**
60 * 建立HttpGet 61 */
62 HttpGet httpGet = new HttpGet(uriBuilder.build()); 63 /**
64 * 設置請求頭部編碼 65 */
66 httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 67 /**
68 * 設置返回編碼 69 */
70 httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8")); 71 /**
72 * 請求服務 73 */
74 response = client.execute(httpGet); 75 /**
76 * 獲取響應嗎 77 */
78 int statusCode = response.getStatusLine().getStatusCode(); 79
80 if (SUCCESS_CODE == statusCode){ 81 /**
82 * 獲取返回對象 83 */
84 HttpEntity entity = response.getEntity(); 85 /**
86 * 經過EntityUitls獲取返回內容 87 */
88 String result = EntityUtils.toString(entity,"UTF-8"); 89 /**
90 * 轉換成json,根據合法性返回json或者字符串 91 */
92 try{ 93 jsonObject = JSONObject.parseObject(result); 94 return jsonObject; 95 }catch (Exception e){ 96 return result; 97 } 98 }else{ 99 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET請求失敗!"); 100 } 101 }catch (Exception e){ 102 LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e); 103 } finally { 104 response.close(); 105 client.close(); 106 } 107 return null; 108 } 109
110 /**
111 * 發送POST請求 112 * @param url 113 * @param nameValuePairList 114 * @return JSON或者字符串 115 * @throws Exception 116 */
117 public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{ 118 JSONObject jsonObject = null; 119 CloseableHttpClient client = null; 120 CloseableHttpResponse response = null; 121 try{ 122 /**
123 * 建立一個httpclient對象 124 */
125 client = HttpClients.createDefault(); 126 /**
127 * 建立一個post對象 128 */
129 HttpPost post = new HttpPost(url); 130 /**
131 * 包裝成一個Entity對象 132 */
133 StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8"); 134 /**
135 * 設置請求的內容 136 */
137 post.setEntity(entity); 138 /**
139 * 設置請求的報文頭部的編碼 140 */
141 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 142 /**
143 * 設置請求的報文頭部的編碼 144 */
145 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8")); 146 /**
147 * 執行post請求 148 */
149 response = client.execute(post); 150 /**
151 * 獲取響應碼 152 */
153 int statusCode = response.getStatusLine().getStatusCode(); 154 if (SUCCESS_CODE == statusCode){ 155 /**
156 * 經過EntityUitls獲取返回內容 157 */
158 String result = EntityUtils.toString(response.getEntity(),"UTF-8"); 159 /**
160 * 轉換成json,根據合法性返回json或者字符串 161 */
162 try{ 163 jsonObject = JSONObject.parseObject(result); 164 return jsonObject; 165 }catch (Exception e){ 166 return result; 167 } 168 }else{ 169 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST請求失敗!"); 170 } 171 }catch (Exception e){ 172 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e); 173 }finally { 174 response.close(); 175 client.close(); 176 } 177 return null; 178 } 179
180 /**
181 * 組織請求參數{參數名和參數值下標保持一致} 182 * @param params 參數名數組 183 * @param values 參數值數組 184 * @return 參數對象 185 */
186 public static List<NameValuePair> getParams(Object[] params, Object[] values){ 187 /**
188 * 校驗參數合法性 189 */
190 boolean flag = params.length>0 && values.length>0 && params.length == values.length; 191 if (flag){ 192 List<NameValuePair> nameValuePairList = new ArrayList<>(); 193 for(int i =0; i<params.length; i++){ 194 nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString())); 195 } 196 return nameValuePairList; 197 }else{ 198 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "請求參數爲空且參數長度不一致"); 199 } 200 return null; 201 } 202 }
1 package com.sinotn.service.impl; 2 3 import com.sinotn.service.HttpClientService; 4 import org.apache.http.NameValuePair; 5 6 import java.util.List; 7 8 /** 9 * 發送post/get 測試類 10 */ 11 public class Test { 12 13 public static void main(String[] args) throws Exception{ 14 String url = "要請求的url地址"; 15 /** 16 * 參數值 17 */ 18 Object [] params = new Object[]{"param1","param2"}; 19 /** 20 * 參數名 21 */ 22 Object [] values = new Object[]{"value1","value2"}; 23 /** 24 * 獲取參數對象 25 */ 26 List<NameValuePair> paramsList = HttpClientService.getParams(params, values); 27 /** 28 * 發送get 29 */ 30 Object result = HttpClientService.sendGet(url, paramsList); 31 /** 32 * 發送post 33 */ 34 Object result2 = HttpClientService.sendPost(url, paramsList); 35 36 System.out.println("GET返回信息:" + result); 37 System.out.println("POST返回信息:" + result2); 38 } 39 }
爲了不須要證書,因此用一個類繼承DefaultHttpClient類,忽略校驗過程。json
寫一個SSLClient類,繼承至HttpClient數組
1 import java.security.cert.CertificateException; 2 import java.security.cert.X509Certificate; 3 import javax.net.ssl.SSLContext; 4 import javax.net.ssl.TrustManager; 5 import javax.net.ssl.X509TrustManager; 6 import org.apache.http.conn.ClientConnectionManager; 7 import org.apache.http.conn.scheme.Scheme; 8 import org.apache.http.conn.scheme.SchemeRegistry; 9 import org.apache.http.conn.ssl.SSLSocketFactory; 10 import org.apache.http.impl.client.DefaultHttpClient; 11 //用於進行Https請求的HttpClient
12 public class SSLClient extends DefaultHttpClient{ 13 public SSLClient() throws Exception{ 14 super(); 15 SSLContext ctx = SSLContext.getInstance("TLS"); 16 X509TrustManager tm = new X509TrustManager() { 17 @Override 18 public void checkClientTrusted(X509Certificate[] chain, 19 String authType) throws CertificateException { 20 } 21 @Override 22 public void checkServerTrusted(X509Certificate[] chain, 23 String authType) throws CertificateException { 24 } 25 @Override 26 public X509Certificate[] getAcceptedIssuers() { 27 return null; 28 } 29 }; 30 ctx.init(null, new TrustManager[]{tm}, null); 31 SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 32 ClientConnectionManager ccm = this.getConnectionManager(); 33 SchemeRegistry sr = ccm.getSchemeRegistry(); 34 sr.register(new Scheme("https", 443, ssf)); 35 } 36 }