SpringBoot 发送网络请求和文件

使用 RestTemplate

  1. 将 RestTemplate注入到容器中
 @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
  1. 发送get请求
 String url = "https://api.example.com/some-endpoint"; // 要请求的URL
        String response = restTemplate.getForObject(url, String.class); // 发送GET请求并获取响应
        return response;
  1. 发送post请求并设置请求体格式
 public String sendHttpPostRequest() {
        String url = "https://api.example.com/post-endpoint"; // 要发送POST请求的URL
        String requestBody = "{\"key\": \"value\"}"; // POST请求的请求体

        HttpHeaders headers = new HttpHeaders();
        //设置请求体中包含的数据类型为json
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        String response = restTemplate.postForObject(url, requestEntity, String.class); // 发送POST请求并获取响应
        return response;
    }
  1. 发送文件并添加其他属性
 public String sendFileWithProperties() throws IOException {
        String url = "https://api.example.com/upload-endpoint"; // 上传文件的URL
        Path filePath = Paths.get("path/to/your/file.txt"); // 文件路径

        // 读取文件内容为字节数组
        byte[] fileBytes = Files.readAllBytes(filePath);

        // 构建请求体,添加文件和其他属性
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new ByteArrayResource(fileBytes) {
            @Override
            public String getFilename() {
                return "file.txt"; // 设置文件名
            }
        });
        
        // 添加其他属性
        body.add("property1", "value1");
        body.add("property2", "value2");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

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

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
			// 处理响应
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
       		 //获取响应体
            return responseEntity.getBody();
        } else {
            return "File upload with properties failed";
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值