总述 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 :
需要引入的依赖:
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();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 ; CloseableHttpClient client = (CloseableHttpClient) SpringContextUtils.getBeanById("httpClient" ); 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); 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 ) ; } }