最近工作中需要對接API,需要用到HTTP請求及處理返回response锌雀,特此記錄。
創(chuàng)建連接,幾種不同的創(chuàng)建方式
HttpClient client = HttpClientBuilder.create().build(); // HttpClient client = HttpClients.createDefault(); // CloseableHttpClient client = HttpClients.createDefault();
初始化URL
String url = "http://localhost:8080/imcallback"; URL target = null; try { target = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); }
創(chuàng)建request
HttpUriRequest request = null; // method try { request = new HttpPost(target.toURI()); // request = new HttpPut(target.toURI()); // request = new HttpGet(target.toURI()); // request = new HttpDelete(target.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); }
給request添加header
for (NameValuePair nameValuePair : header.getHeaders()) { request.addHeader(nameValuePair.getName(), nameValuePair.getValue()); }
給request添加body(具體包含json格式字符串還是其他格式需自行處理)
if (null != body) { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(body.toString(), "UTF-8")); }
創(chuàng)建response洲炊,執(zhí)行并獲得response
HttpResponse response; //CloseableHttpResponse response = null; try { response = client.execute(request); } catch (IOException e) { e.printStackTrace(); }
處理狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
獲得內容
HttpEntity entity = response.getEntity(); //獲得JSON對象 ObjectNode responseNode = (ObjectNode) EntityUtils.toString(response.getEntity(), "UTF-8");
具體JSON的處理用到了jackson吨悍。
最后關閉
finally { try { response.close(); client.close(); } catch (Exception e) { e.printStackTrace(); }
需要httpclient4.3.3以上定拟,maven配置如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.3.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>