总述

http请求无论请求类型,大体分为2部分,即Headers请求头与Body请求体。
对于请求体来说:
Get的请求体params以明文的形式拼接到url后边,以?为分隔符;
Post的请求体以body的形式传递,大体上以key-value的形式存在,无论是表单还是json格式的数据,其中key为判断标识不可为null,而value可以为null。

Content-Type常见类型

  • text/html : HTML格式
  • text/plain :纯文本格式
  • text/xml : XML格式
  • image/gif :gif图片格式
  • image/jpeg :jpg图片格式
  • image/png:png图片格式
  • application/xhtml+xml :XHTML格式
  • application/xml : XML数据格式
  • application/atom+xml :Atom XML聚合格式
  • application/json : JSON数据格式
  • application/pdf :pdf格式
  • application/msword : Word文档格式
  • application/octet-stream : 二进制流数据
  • multipart/form-data : 需要在表单中进行文件上传的格式
  • application/x-www-form-urlencoded :
    中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

需要引入的依赖:

1
2
3
4
5
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>

Get请求

Content-Type为数据传递的格式,一般必填
剩余可根据需求向请求头加入约定参数,同样是key-value的形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
int status = response.getStatusLine().getStatusCode();//获取http响应码
if (status != 200) {
return;
}

// 获取响应数据
String result = EntityUtils.toString(entity, "UTF-8");
response.close();
client.close();

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
// 请求返回结果
String resultJson = null; // 创建Client
CloseableHttpClient client = (CloseableHttpClient) SpringContextUtils.getBeanById("httpClient"); // 创建HttpPost对象
HttpPost httpPost = new HttpPost();
try {
// 设置请求地址
httpPost.setURI(new URI(url)); // 设置请求头
if (headers != null) { Header[] allHeader = new BasicHeader[headers.size()];
int i = 0;
for (Map.Entry<String, String> entry : headers.entrySet()) {
allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
i++;
}
httpPost.setHeaders(allHeader);
}
// 设置实体
StringEntity entity; entity = new StringEntity(jsonBody, encoding);
httpPost.setEntity(entity);
// 发送请求,返回响应对象
CloseableHttpResponse response = client.execute(httpPost);
// 设置连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);

// 获取响应状态
int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) {
// 获取响应结果
resultJson = EntityUtils.toString(response.getEntity(), encoding); } else {
logger.error("响应失败,状态码:{}", status);
}
} catch (Exception e) {
logger.error("发送post请求失败", e);
} finally {
httpPost.releaseConnection();
}

body为纯字符格式

body含有二进制文件格式

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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class HuabotRestHttpUtil {
private HuabotRestHttpUtil() {
restTemplate = new RestTemplate();
}

@Autowired
private static RestTemplate restTemplate;

public static String postWithFile(String url, String charSet, String fileKey, String filePath, MultiValueMap<String, Object> body, MultiValueMap<String, String> headers) {
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName(charSet)));

//设置请求头
HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.addAll(headers);
MediaType type = new MediaType("multipart", "form-data", Charset.forName(charSet));
httpHeaders.setContentType(type);

//设置请求体,注意是LinkedMultiValueMap
FileSystemResource fileSystemResource = new FileSystemResource(filePath); body.add(fileKey, fileSystemResource);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
return restTemplate.postForObject(url, httpEntity, String.class);
}
}