最近工作中需要对接API,需要用到HTTP请求及处理返回response,特此记录。
创建连接,几种不同的创建方式
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(); }
创建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")); }
创建response,执行并获得response
HttpResponse response; //CloseableHttpResponse response = null; try { response = client.execute(request); } catch (IOException e) { e.printStackTrace(); }
处理状态码
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>