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

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