首页 > 其他分享 >spring boot发送http

spring boot发送http

时间:2023-05-16 16:44:22浏览次数:46  
标签:http String url spring boot return headers new public

 public static <T> T doGet(String url, Class<T> responseType, Map<String, Object> paramMap) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1000);
        restTemplate.setRequestFactory(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Access-token",token);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            builder.queryParam(entry.getKey(), entry.getValue());
        }
        ResponseEntity<T> responseEntity = restTemplate.exchange(builder.buildAndExpand().toUriString(), HttpMethod.GET, entity, responseType);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        throw new RuntimeException("Failed to send get");
    }

    public static <T> T doPost(String url, Class<T> responseType, Object requestObject) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1000);
        restTemplate.setRequestFactory(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestObject, headers);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return responseEntity.getBody();
    }

    public static <T> T doPostJson(String url, Class<T> responseType,  String params){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1000);
        restTemplate.setRequestFactory(requestFactory);

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Access-token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        throw new RuntimeException("Failed to send post");
    }


    public static JSONObject uploadFile(String url,MultipartFile file) throws IOException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1000);
        restTemplate.setRequestFactory(requestFactory);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", convert(file));

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                JSONObject.class
        );
        return responseEntity.getBody();
    }

    private static ByteArrayResource convert(MultipartFile file) {
        ByteArrayResource resource = null;
        try {
            resource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resource;
    }

    public static MultipartFile downloadFile(String url) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
        byte[] fileBytes = response.getBody();
        ByteArrayResource resource = new ByteArrayResource(fileBytes);
        String fileName = getFileName(url, response.getHeaders().getContentType());
        Path tempFile = Files.createTempFile(fileName, ".tmp");
        Files.write(tempFile, fileBytes);
        return new MultipartFile() {
            @Override
            public String getName() {
                return fileName;
            }

            @Override
            public String getOriginalFilename() {
                return fileName;
            }

            @Override
            public String getContentType() {
                return response.getHeaders().getContentType().toString();
            }

            @Override
            public boolean isEmpty() {
                return fileBytes == null || fileBytes.length == 0;
            }

            @Override
            public long getSize() {
                return fileBytes.length;
            }

            @Override
            public byte[] getBytes() throws IOException {
                return fileBytes;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return resource.getInputStream();
            }

            @Override
            public void transferTo(File dest) throws IOException, IllegalStateException {
                Files.copy(tempFile, dest.toPath());
            }
        };
    }

    private static String getFileName(String url, MediaType mediaType) {
        String extension = "";
        String contentType = mediaType.toString();
        if (contentType.contains("/")) {
            extension = "." + contentType.split("/")[1];
        }
        String[] parts = url.split("/");
        String fileName = parts[parts.length - 1];
        if (fileName.contains(".")) {
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
        }
        fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_") + extension;
        return fileName;
    }

    public static void downloadFile(String url, String localFilePath) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));

        RequestCallback requestCallback = request -> {
            request.getHeaders().addAll(headers);
        };

        ResponseExtractor<Void> responseExtractor = response -> {
            MediaType contentType = response.getHeaders().getContentType();
            String fileExtension = contentType.getSubtype();
            String contentDisposition = response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
            String filename;
            if (contentDisposition != null && contentDisposition.contains("filename=")) {
                filename = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9);
                filename = filename.replaceAll("\"", "");
            } else {
                filename = getFileName(url, response.getHeaders().getContentType());
            }
            FileOutputStream outputStream = new FileOutputStream(new File(localFilePath + filename + "." + fileExtension));
            InputStream inputStream = response.getBody();
            FileCopyUtils.copy(inputStream, outputStream);
            return null;
        };

        restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
    }

标签:http,String,url,spring,boot,return,headers,new,public
From: https://www.cnblogs.com/holdme/p/17406100.html

相关文章

  • Spring源码:Bean生命周期(五)
    前言在上一篇文章中,我们深入探讨了Spring框架中Bean的实例化过程,该过程包括从Bean定义中加载当前类、寻找所有实现了InstantiationAwareBeanPostProcessor接口的类并调用实例化前的方法、进行实例化、调用applyMergedBeanDefinitionPostProcessors方法等多个步骤,最终生......
  • springmvc上传文件——疯狂踩坑
    添加依赖: 配置:注意这里bean的id必须为 multipartResolver 实现:这里需要注意圈起来的地方的名字和文件上传时候的字段名称需要保持一致  测试:这里键名必须为upload和上面那张图中的upload对应publicResultuploadResFile(@RequestParamMultipartFileupload,Ht......
  • 服务器 nginx 前端配置 SSL 证书并能访问 HTTPS
    安装以下步骤,按图索骥即可。 首先,没安装nginx的去这个地址,安装nginx。本人版本是(1.18.0).https://nginx.org/安装好了之后,在nginx目录下执行cmd运行命令nginx.exe-V出现以下情况就证明nginx自带了SSL模块了,不需要额外安装 有了上面这个东西之后,nginx底下......
  • Unable to bind to http://localhost:xxxx on the IPv4 loopback interface: '以一种
    这个错误大概率是端口冲突, 这里不再赘述。具体(参考https://www.cnblogs.com/zhengdongdong/p/12001152.html)我这边的原因是运行端口在被排除端口范围中(参考https://gsw945.com/index.php/archives/33/)cmd运行 netshinterfaceipv4showexcludedportrangeprotocol=tcp......
  • SpringBoot优化之项目启动优化
    目录1SpringBoot启动优化1.1背景1.2观察SpringBoot启动run方法1.2.1SpringApplicationRunListener接口1.2.2使用SpringApplicationRunListener监控1.3监控Bean注入耗时1.3.1BeanPostProcessor接口1.4优化方案1.4.1如何解决扫描路径过多1.4.2如何解决Bean初始......
  • spring-transaction源码分析(4)AspectJ和spring-aspects模块
    AspectJ是Java语言实现的一个面向切面编程的扩展库,能够基于一定的语法编写Aspect代码,使用ajc编译器将其编译成.class文件,之后在Java程序编写或加载时将Aspect逻辑嵌入到指定的切面。安装AspectJ下载AspectJ到官网下载安装包:http://www.eclipse.org/downloads/download.php?fil......
  • Spring 3 & jBPM 5 & LocalTaskService
    帖子地址:[url]https://community.jboss.org/thread/195386[/url]HiGuys,IamalsostrugglinginconfigSpring+LocalHumanTask.Iamusing[color=red][b]Spring3.0,JBPM5.4.0.Final,Drools5.5.0.Final[/b][/color]IcanconfigtouseJTA......
  • C# HttpClient发送Get和Post请求
     HttpClient发送Get和Post请求 publicclassHttpHelper{///<summary>///发起POST同步请求//////</summary>///<paramname="url"></param>///<paramname="postData&q......
  • springboot 整合webservice 相关说明
    1.环境依赖jdk8,springboot2.3.12.release,cxf版本需要根据springboot版本修改,方法:查看springboot版本的发布日期,然后根据日期找相近的两个版本<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><versi......
  • Spring中实现文件上传
    一些问题:springmvc文件上传,使用它的MultipartHttpServletRequest,tomcat中正常,resion中报错[url]http://zhupan.iteye.com/blog/26427[/url]实现图片上传用户必须能够上传图片,因此需要文件上传的功能。比较常见的文件上传组件有CommonsFileUpload(htt......