RestTemplate的常见使用

1.配置(注入)

         由于RestTemplate没有被自动注入到容器中,所以需要自己注入。选其一就可以。

@Configuration
public class ConfigBean{
    @Bean
    public RestTemplate getRestTemplate(){
         return new RestTemplate();
    }
}
@Configuration
public class RedisConfig {
   @Bean
   public RestTemplate restTemplate(RestTemplateBuilder builder) {
      RestTemplate restTemplate = builder.build();
      restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
      return restTemplate;
   }
}

2.自动装配

@Autowired
private RestTemplate restTemplate;

3.具体的一些使用

提示:在请求头中也可以根据业务的需求进行参数的添加,根据自己需求都可以进行变动

Post请求,请求头规定数据格式:Content-Type=application/json;(发送的数据类型为JSON)

Post请求在请求的body中模拟JSON数据

PostMan中这种类型:

{
	"pageNo":1,
	"pageSize":2,
	"filePath":"/MANUAL_DIAGNOSIS_CASE_ATTACHED_FILE",
	"fileServiceCategory":"MANUAL_DIAGNOSIS_CASE_ATTACHED_FILE"
}
public static JSONObject sendSearchForKnow(String url, int pageNo, int pageSize, String searchWord, String filePath, String fileServiceCategory) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置请求体(请求参数)
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNo", pageNo);
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("searchWord", searchWord);
        jsonObject.put("filePath", filePath);
        jsonObject.put("fileServiceCategory", fileServiceCategory);
        //用httpEntity封装整个报文
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
        //发送
        ResponseEntity<JSONObject> entity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
        return entity.getBody();
    }

post请求,请求头规定数据格式:Content-Type="application/x-www-form-urlencoded"(发送的数据类型为键值对)

public static JSONObject createFolderForKnow(String url, String filePath) {
    //设置请求头
    HttpHeaders headers = new HttpHeaders();
    //headers.add("Content-Type", "application/x-www-form-urlencoded");
     headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //设置请求参数
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    param.add("filePath", filePath);
    //用HttpEntity封装整个报文
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
    //发送
    ResponseEntity<JSONObject> entity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
    return entity.getBody();

文件上传

  • Post请求 数据类型为:Content-Type=multipart-from-data

  • post以表单进行提交

public static JSONObject uploadDocToKnow(String url, File file, String filePath, String fileServiceCategory) throws IOException {
    //设置请求头
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    //设置请求参数
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    FileSystemResource fileSystemResource = new FileSystemResource(file);
    param.add("files", fileSystemResource);
    param.add("filePath", filePath);
    param.add("fileServiceCategory", fileServiceCategory);
    //用HttpEntity封装整个报文
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
    //发送
    ResponseEntity<JSONObject> entity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);//url,HttpEntity,返回数据类型
    return entity.getBody();
}

文件下载

get请求,参数是拼接的,不是/{id}类型

public static void downloadForKnow(String url, HttpServletResponse response, String fileId) throws IOException {
    //设置请求头
    HttpHeaders headers = new HttpHeaders();
    url = url + "?fileId=" + fileId;
    //用HttpEntity封装整个报文
    HttpEntity<byte[]> httpEntity = new HttpEntity<>(headers);
    //发送请求
    ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, byte[].class);
    //获取响应的请求体(为了获取文件的名称)
    HttpHeaders headersForKnow = exchange.getHeaders();
    List<String> strings = headersForKnow.get("content-disposition");
    String[] split = strings.get(0).split(";");
    String fileNameEncode = split[1].split("=")[1];
    log.info(fileNameEncode);

    //去设置response
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setHeader("Content-disposition",
                       "attachment; filename =" + fileNameEncode);
	//进行流输出
    try (InputStream inputStream = new ByteArrayInputStream(exchange.getBody());
         BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
        byte[] buff = new byte[1024*1000];
        int bytesRead;
        while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bos.flush();
        log.info("下载成功");
    } catch (IOException e) {
        e.printStackTrace();
    }

附带:

以application开头的媒体格式类型:

application/xhtml+xml :XHTML格式

application/xml : XML数据格式

application/atom+xml :Atom XML聚合格式

application/json : JSON数据格式

application/pdf :pdf格式

application/msword : Word文档格式

application/octet-stream : 二进制流数据(如常见的文件下载)

application/x-www-form-urlencoded :form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

另外一种常见的媒体格式是上传文件之时使用的: Content-Type = multipart-from-data

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章