HttpClient的使用
|字数总计:3.5k|阅读时长:16分钟|阅读量:|
HttpClient官网
本文参考地址:【CSDN】HttpClient详细使用示例 justry_deng
HttpClient主要用于访问其他接口
准备
引入相关依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
|
fastjson有将对象转化为json字符串的功能等。
这里使用的是4.5版本的httpclient,各个版本在使用上会有差异。
用于以下案例的测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @RestController public class MyController {
@GetMapping("/doGet1") public String doGet1() { return "这个Get请求没有任何参数"; }
@GetMapping("/doGet2") public String doGet2(String name, Integer age) { return name + "今年" + age + "岁了"; }
@PostMapping("/doPost1") public String doPost1() { return "这个Post请求没有任何参数"; }
@PostMapping("/doPost2") public String doPost2(String name, Integer age) { return name + "今年" + age + "岁了"; }
@PostMapping("/doPost3") public String doPost3(@RequestBody User user) { return user.toString(); }
@PostMapping("/doPost4") public String doPost4(@RequestBody User user, Integer flag, String meaning) { return user.toString() + "\n" + flag + ">>>" + meaning; } }
|
GET方式
无参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public static void doGet1() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://localhost:8080/doGet1"); CloseableHttpResponse response = null; try { response = httpClient.execute(httpGet); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (Exception e) { e.printStackTrace(); } } }
|
有参方式一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public static void doGet2() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); StringBuilder params = new StringBuilder(); try { params.append("name=") .append(URLEncoder.encode("阿楠", "utf-8")) .append("&") .append("age=24"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
HttpGet httpGet = new HttpGet("http://localhost:8080/doGet2" + "?" + params); CloseableHttpResponse response = null; try { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .setSocketTimeout(5000) .setRedirectsEnabled(true).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
有参方式二
- 将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public static void doGet3() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); URI uri = null; try { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("name", "阿楠")); params.add(new BasicNameValuePair("age", "18")); uri = new URIBuilder().setScheme("http").setHost("localhost") .setPort(8080).setPath("/doGet2") .setParameters(params).build(); } catch (URISyntaxException e) { e.printStackTrace(); } HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null; try { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .setSocketTimeout(5000) .setRedirectsEnabled(true).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
POST方式
无参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public static void doPost1() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://localhost:8080/doPost1"); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
有参(普通参数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public static void doPost2() { CloseableHttpClient httpClient = HttpClientBuilder.create().build();
StringBuilder params = new StringBuilder(); try { params.append("name=").append(URLEncoder.encode("nan", "utf-8")) .append("&") .append("age=24"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
HttpPost httpPost = new HttpPost("http://localhost:8080/doPost2" + "?" + params);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
有参(对象参数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public static void doPost3() { CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:8080/doPost3"); User user = new User(); user.setName("霍华德"); user.setAge(35); user.setGender("男"); user.setMotto("扣篮要暴力~");
String jsonString = JSON.toJSONString(user);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
有参(普参+对参)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public static void doPost4(){ CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URI uri = null; try { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("flag", "4")); params.add(new BasicNameValuePair("meaning", "这是普通参数")); uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080) .setPath("/doPost4").setParameters(params).build(); } catch (URISyntaxException e) { e.printStackTrace(); }
HttpPost httpPost = new HttpPost(uri);
User user = new User(); user.setName("霍华德"); user.setAge(35); user.setGender("男"); user.setMotto("扣篮要暴力~");
StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine());
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } EntityUtils.consume(responseEntity); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
GET和POST请求封装
DTO对象的封装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
public class ApiRequest {
private String apiUrl;
private Long callTimeStamp;
private Integer returnCode;
private Object request;
private Object result;
public String getApiUrl() { return apiUrl; }
public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; }
public Long getCallTimeStamp() { return callTimeStamp; }
public void setCallTimeStamp(Long callTimeStamp) { this.callTimeStamp = callTimeStamp; }
public Integer getReturnCode() { return returnCode; }
public void setReturnCode(Integer returnCode) { this.returnCode = returnCode; }
public Object getRequest() { return request; }
public void setRequest(Object request) { this.request = request; }
public Object getResult() { return result; }
public void setResult(Object result) { this.result = result; }
@Override public String toString() { return "ApiRequest{" + "apiUrl='" + apiUrl + '\'' + ", callTimeStamp=" + callTimeStamp + ", returnCode=" + returnCode + ", request=" + request + ", result=" + result + '}'; } }
|
调用接口的封装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
| public class ApiUtil {
public static final String CHARSET = "UTF-8"; public static final Integer SUCCESS_CODE = 200; public static final Integer ERROR_CODE = 400;
public static ApiRequest request(String method, String url, Map<String, String> params) throws Exception { if (method == null) { throw new RuntimeException("指定请求方式POST/GET"); } else if (method.equalsIgnoreCase("GET")) { return doGet(url, params); } else if (method.equalsIgnoreCase("POST")) { return doPost(url, params); } else { throw new RuntimeException("指定请求方式POST/GET"); } }
public static ApiRequest doGet(String url, Map<String, String> params) { RequestConfig config = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
ApiRequest apiRequest = new ApiRequest(); apiRequest.setApiUrl(url); apiRequest.setReturnCode(ERROR_CODE); apiRequest.setCallTimeStamp(null); apiRequest.setRequest(params); apiRequest.setResult(null);
if (StringUtils.isBlank(url)) { return apiRequest; }
if (params != null && !params.isEmpty()) { try { List<NameValuePair> pairs = new ArrayList<>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs), CHARSET); } catch (IOException e) { e.printStackTrace(); } } HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null;
try { long startTimeStamp = System.currentTimeMillis(); response = httpClient.execute(httpGet); long endTimeStamp = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != SUCCESS_CODE) { apiRequest.setCallTimeStamp(endTimeStamp - startTimeStamp); httpGet.abort(); }
HttpEntity entity = response.getEntity(); if (entity != null) { apiRequest.setReturnCode(SUCCESS_CODE); apiRequest.setCallTimeStamp(endTimeStamp - startTimeStamp); String result = EntityUtils.toString(entity, CHARSET); JSONObject resultOj = JSONObject.parseObject(result); apiRequest.setResult(resultOj); } EntityUtils.consume(entity); } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return apiRequest; }
public static ApiRequest doPost(String url, Map<String, String> params) { RequestConfig config = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
ApiRequest apiRequest = new ApiRequest(); apiRequest.setApiUrl(url); apiRequest.setReturnCode(ERROR_CODE); apiRequest.setCallTimeStamp(null); apiRequest.setRequest(params); apiRequest.setResult(null);
if (StringUtils.isBlank(url)) { return apiRequest; }
HttpPost httpPost = new HttpPost(url); if (params != null && !params.isEmpty()) { try { List<NameValuePair> pairs = new ArrayList<>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
CloseableHttpResponse response = null; try { long startTimeStamp = System.currentTimeMillis(); response = httpClient.execute(httpPost); long endTimeStamp = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != SUCCESS_CODE) { apiRequest.setCallTimeStamp(endTimeStamp - startTimeStamp); httpPost.abort(); }
HttpEntity entity = response.getEntity(); if (entity != null) { apiRequest.setReturnCode(SUCCESS_CODE); apiRequest.setCallTimeStamp(endTimeStamp - startTimeStamp); String result = EntityUtils.toString(entity, CHARSET); JSONObject resultOj = JSONObject.parseObject(result); apiRequest.setResult(resultOj); } EntityUtils.consume(entity); } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return apiRequest; } }
|