zoukankan      html  css  js  c++  java
  • 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);
    
        }
  • 相关阅读:
    P5304旅行者(比bk201还要流氓的解法)
    考试T1护花
    考试T2修剪草坪
    考试T3麻将
    账号密码
    T7
    P2885 [USACO07NOV]电话线Telephone Wire
    P4965 薇尔莉特的打字机
    P1505 [国家集训队]旅游
    T2
  • 原文地址:https://www.cnblogs.com/qq376324789/p/13323178.html
Copyright © 2011-2022 走看看