http请求类、RestTemplate、请求工具类


public class HttpUtils {

public static void main(String[] args) {

}

public static String clientPost(String url,Object params){
HttpMethod method =HttpMethod.POST;
return client(url,method,params);
}

public static String clientGet(String url){
HttpMethod method =HttpMethod.GET;
return client(url,method,null);
}

public static String client(String url, HttpMethod method, Object params){
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","application/json; charset=utf-8");
return clientSetHeaders(url,method,params,headers);
}

public static String clientSetHeaders(String url, HttpMethod method, Object params,HttpHeaders headers){
RestTemplate client = new RestTemplate();
HttpEntity<Object> requestEntity = new HttpEntity<>(params, headers);
// 执行HTTP请求
ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
return response.getBody();
}


}

 

 引包

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

 调用上传文件接口案例

    public static void main(String[] args) throws Exception {

        final String filePath = "D:";
        final String fileName = "a.pdf";

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);

        //设置请求体,注意是LinkedMultiValueMap
        FileSystemResource fileSystemResource = new FileSystemResource(filePath+"/"+fileName);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("filename",fileName);

        HttpMethod method =HttpMethod.POST;
        String s1 = HttpUtils.clientSetHeaders(FILE_URL, method, form, headers);

        System.out.println(s1);

    }

 

上一篇:HttpClient调用接口,参数类型为文件;RestTemplate 调用接口。


下一篇:记录一下restTemplate返回空对象