0%

通过httpclient发送GET和POST请求

通过httpclient POST请求上传文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("http://localhost:8080/upload");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

// 可以添加File或者InputStream
builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, filename);
builder.addTextBody("name", name);

HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
Integer httpCode = response.getStatusLine().getStatusCode();

if (HttpStatus.SC_OK != httpCode) {
throw new RuntimeException("failed...");
}

// 处理responseEntity
String respEntity = EntityUtils.toString(response.getEntity());

GET请求

1
2
3
4
5
6
7
8
9
10
11
12
CloseableHttpClient httpClient = HttpClients.createDefault();

// URL的拼接
URI uri = new URI("http://localhost:8080").resolve("result");
HttpGet httpGet = new HttpGet(uri);

CloseableHttpResponse response = httpClient.execute(httpGet);
Integer httpCode = response.getStatusLine().getStatusCode();

if (HttpStatus.SC_OK != httpCode) {
throw new RuntimeException("failed...");
}

判断请求返回的内容类型

1
2
3
4
5
6
ContentType contentType = ContentType.getOrDefault(response.getEntity());
if (MediaType.APPLICATION_JSON_VALUE.equals(contentType.getMimeType())) {

} else if (MediaType.TEXT_PLAIN_VALUE.equals(contentType.getMimeType())) {

}