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);
    
        }
  • 相关阅读:
    数据库
    java语法
    《Lucene实战(第2版)》 配书代码在IDEA下的编译方法
    lucene学习
    社交关系调研(费)
    微博开发平台java SDK demo学习之examples(demo)
    微博开发平台java SDK demo学习之friendships
    F. Classical? (数论 + 思维 + 推理 + 容斥)
    石子合并问题,经典区间DP
    luoguP2048 [NOI2010]超级钢琴
  • 原文地址:https://www.cnblogs.com/qq376324789/p/13323178.html
Copyright © 2011-2022 走看看