今天本来想在网上找一个HttpCline调用第三方借口的方法,现在网上各种版本,自己在以前做过的项目里找到了一个工具类,感觉挺方便的:里面包括了get请求带参数,get不带参数,post带参数,post不带参数!
添加依赖;
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency>
@SuppressWarnings("deprecation") public class HttpClientUtil { private static final String charset = "utf-8"; public static String get(String reqURL, Map<String, Object> params) { String queryString = ""; if (!StringUtils.contains(reqURL, "?")) { queryString += "?"; } for (Entry<String, Object> entry : params.entrySet()) { queryString += ("&" + entry.getKey()) + "=" + (String.valueOf(entry.getValue())); } queryString = queryString.replace("?&", "?"); return get(reqURL + queryString); } public static byte[] getStream(String reqURL) { CloseableHttpClient httpclient = HttpClients.custom().build(); try { HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000).setConnectTimeout(5000) .setConnectionRequestTimeout(5000).build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpGet); try { HttpEntity entity = response.getEntity(); // 获取响应实体 byte in2b[] = instreamToByte(entity.getContent()); return in2b; } catch (IOException e) { } finally { response.close(); } } catch (IOException e1) { } finally { try { httpclient.close(); } catch (IOException e) { } } return null; } private static byte[] instreamToByte(InputStream input) throws IOException { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[4096]; int n = 0; while (-1 != (n = input.read(buff))) { swapStream.write(buff, 0, n); } byte[] in2b = swapStream.toByteArray(); return in2b; } public static String get(String reqURL) { CloseableHttpClient httpclient = HttpClients.custom().build(); try { HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000).setConnectTimeout(5000) .setConnectionRequestTimeout(5000).build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpGet); try { HttpEntity entity = response.getEntity(); // 获取响应实体 Charset respCharset = ContentType.getOrDefault(entity) .withCharset(charset).getCharset(); return EntityUtils.toString(entity, respCharset); } catch (IOException e) { } finally { response.close(); } } catch (IOException e1) { } finally { try { httpclient.close(); } catch (IOException e) { } } return null; } public static String postJson(String reqURL, Object param) { SSLConnectionSocketFactory sslsf = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial( null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory(sslContext); } catch (KeyManagementException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (KeyStoreException e) { return null; } CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf).build(); try { RequestBuilder builder = RequestBuilder.post(reqURL); if (param != null) { StringEntity stringEntity = new StringEntity(JSON.toJSONString(param), charset); builder.setEntity(stringEntity); } HttpUriRequest post = builder.build(); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); Charset respCharset = ContentType.getOrDefault(entity) .withCharset(charset).getCharset(); String result = EntityUtils.toString(entity, respCharset); EntityUtils.consume(entity); return result; } finally { response.close(); } } catch (IOException e) { } finally { try { httpclient.close(); } catch (IOException e) { } } return null; } public static String postForm(String reqURL, Map<String, Object> params) { CloseableHttpClient httpclient = HttpClients.custom().build(); try { RequestBuilder builder = RequestBuilder.post(reqURL); builder.setCharset(Charset.forName(charset)); MultipartEntity httpEntity = new MultipartEntity(); if (params != null) { for (Entry<String, Object> entry : params.entrySet()) { FormBodyPart formBodyPart = new FormBodyPart( entry.getKey(), new StringBody(String.valueOf(entry .getValue()), "text/plain", Charset.forName(charset))); httpEntity.addPart(formBodyPart); } } builder.setEntity(httpEntity); HttpUriRequest post = builder.build(); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); Charset respCharset = ContentType.getOrDefault(entity) .withCharset(charset).getCharset(); String result = EntityUtils.toString(entity, respCharset); EntityUtils.consume(entity); return result; } finally { response.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { } } return null; } public static void main(String args[]) throws IOException { //TODO 测试 } }
请求头里面添加 secret 请求借口; httpGet.setHeader("X-Mall-Token", xxxx);
/** * 第三方借口对接 */ public static String httpClientGet(Map<String, Object> params) { StringBuffer resultBuffer = null; HttpClient client = new DefaultHttpClient(); BufferedReader br = null; // 构建请求参数 StringBuffer sbParams = new StringBuffer(); if (params != null && params.size() > 0) { for (Map.Entry<String, Object> entry : params.entrySet()) { sbParams.append(entry.getKey()); sbParams.append("="); try { sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()))); } catch (Exception e) { throw new RuntimeException(e); } sbParams.append("&"); } } if (sbParams != null && sbParams.length() > 0) { loan_url = loan_url + "?" + sbParams.substring(0, sbParams.length() - 1); } HttpGet httpGet = new HttpGet(loan_url); httpGet.setHeader("X-Mall-Token", secret); try { HttpResponse response = client.execute(httpGet); // 读取服务器响应数据 br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String temp; resultBuffer = new StringBuffer(); while ((temp = br.readLine()) != null) { resultBuffer.append(temp); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { br = null; throw new RuntimeException(e); } } } return resultBuffer.toString(); }
当你在解析第三方返回数据时候一般我们会用;
JSONObject jsonObject = JSONObject.parseObject(result);
然后处理返回数据!