将一个服务器通过HTTP请求另一个服务器

时间:2023-08-26
本文章向大家介绍将一个服务器通过HTTP请求另一个服务器,主要内容包括1.一个服务器访问另一个服务器(不传参)、2.一个服务器访问另一个服务器(传参)、3.一个服务器访问另一个服务器(传对象)、4.一个服务器访问另一个服务器(MultipartFile文件传输)、使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.一个服务器访问另一个服务器(不传参)

    @RequestMapping ("/test")
    public ResponseEntity<String> serverToServerRequest() {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
  // 设置目标服务器的URL
        String targetUrl = "http://localhost:9172/file/test";

        // 创建请求体
        HttpEntity<String> requestEntity = new HttpEntity<>(null);

        // 发送 POST 请求给目标服务器,并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(targetUrl, requestEntity, String.class);

        // 返回目标服务器的响应
        return response;
    }

2.一个服务器访问另一个服务器(传参)

    @RequestMapping ("/test")
    public ResponseEntity<String> serverToServerRequest() {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        Integer a = 5;

        // 设置目标服务器的URL
        String targetUrl = "http://localhost:9172/file/test1?a="+a;

        // 创建请求体
        HttpEntity<String> requestEntity = new HttpEntity<>(null);

        // 发送 POST 请求给目标服务器,并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(targetUrl, requestEntity, String.class);

        // 返回目标服务器的响应
        return response;
    }

3.一个服务器访问另一个服务器(传对象)

 @RequestMapping ("/test2")
    public ResponseEntity<String> serverToServerRequest2() {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        ClassEntity classEntity = new ClassEntity();
        classEntity.setClassName("这是一个测试");
        System.out.println(classEntity);

        // 设置目标服务器的URL
        String targetUrl = "http://localhost:9172/file/test2";

        // 创建请求体
        HttpEntity<ClassEntity> requestEntity = new HttpEntity<>(classEntity);

        // 发送 POST 请求给目标服务器,并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(targetUrl, requestEntity, String.class);

        // 返回目标服务器的响应
        return response;
    }

4.一个服务器访问另一个服务器(MultipartFile文件传输)

package com.dashan.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("test")
public class FileUploadController {

    @PostMapping("/upload")
    public String uploadFile( MultipartFile file) throws IOException {
        // 创建临时文件
        File tempFile = File.createTempFile("temp-", "-" + file.getOriginalFilename());

        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) {
            // 将接收到的文件内容写入临时文件
            byte[] bytes = file.getBytes();
            outputStream.write(bytes);
        }catch (IOException e){
            //处理异常
        }

        // 将临时文件传输给另一个服务器的接口
        // 这里可以使用 HttpClient、RestTemplate 或其他 HTTP 客户端工具发送文件
        // 示例使用 RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        String targetUrl = "http://localhost:9172/file/upload";

        // 发送文件
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(tempFile));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.POST, requestEntity, String.class);

        // 删除临时文件
        Files.deleteIfExists(tempFile.toPath());
        System.out.println( responseEntity.getBody());
        JsonObject jsonObject = JsonParser.parseString(responseEntity.getBody()).getAsJsonObject();
        String fieldValue = jsonObject.get("data").getAsString();
        System.out.println(fieldValue);

        return responseEntity.getBody();
    }
}

在方法内部,首先创建一个临时文件,并将接收到的文件内容写入临时文件中。然后使用Java标准库中的HttpClient发送POST请求到另一个服务器的接口uploadUrl,将临时文件作为请求的内容。最后根据另一个服务器返回的响应码判断文件是否成功传输,并返回相应的响应给客户端。

原文地址:https://www.cnblogs.com/xbinbin/p/17658470.html