【问题标题】:How to perform an http request to another server from spring boot controller如何从 Spring Boot 控制器向另一台服务器执行 http 请求
【发布时间】:2021-08-31 05:10:53
【问题描述】:

我想从托管在 localhost:8080 上的 Spring Boot 应用程序对托管在 localhost:80 上的服务器(例如,但可能是每个主机)执行 get 请求。

例如,我想从我的 spring 应用程序中获取托管在 locahost:80/image.jpg 上的图像。我该如何处理?

【问题讨论】:

    标签: spring http get-request


    【解决方案1】:

    您可以为此使用 RestTemplate。

            RestTemplate restTemplate = new RestTemplate();
    
            String uri = localhost:80; // or any other uri
    
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
    
            HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
            ResponseEntity<?> result =
                    restTemplate.exchange(uri, HttpMethod.GET, entity, returnClass);
            return result.getBody();
    

    如果要获取图片,请使用以下方法:

    String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg";
    byte[] imageBytes = restTemplate.getForObject(url, byte[].class);
    Files.write(Paths.get("image.jpg"), imageBytes);
    

    您还需要在应用程序配置中配置 ByteArrayHttpMessageConverter:

    @Bean
    public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) {
        return new RestTemplate(messageConverters);
    }
    
    @Bean
    public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
        return new ByteArrayHttpMessageConverter();
    }
    

    【讨论】:

    • 这返回一个 Json/string 格式,如果我想要一个图像呢?
    • 我敢打赌我什至应该更改 restTemplate.exchange 的签名。第三个参数是“returnClass”,我应该为图像更改什么?
    • 对不起,我一直不理解。它在哪里保存图像?我可以在哪里编辑“应用程序配置”
    • 它将图像保存在您将在 Paths.get() 中指定的路径中,并创建一个新的 java 类并使用 @Configuration 对其进行注释。您放入的任何 Bean 都将添加到应用程序配置中。
    【解决方案2】:

    如果你想用 spring 发送请求,你可以这样做

    //first create e restemplate variable
    RestTemplate restTemplate=new RestTemplate();
    
    //you can create and edit header
    HttpHeaders header= new HttpHeaders();
    header.add("Authorization", "*****************");
    header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    header.add("Accept", "application/json");
    
    //you can create and edit body to
    MultiValueMap<String, String> body= new LinkedMultiValueMap<String, String>();
    body.add("grant_type", "client_credentials");
    
    HttpEntity<MultiValueMap<String, String>> requeteHttp =new HttpEntity<MultiValueMap<String, String>>(body, header);
    
    //After you can create a request
    ResponseEntity<Response_class> reponse = restTemplate.postForEntity("your api link", requeteHttp , Response_class.class);
    //if you want to send a get request you can edit postForEntity to get
    

    关于 Response_class 如果你知道请求的返回类型,你可以在这里创建一个类并使用它,否则你可以使用字符串代替

    如果您的请求返回这样的 json

    {
        "token_type":"***",
        "access_token":"***",
        "expires_in":"***",
    }
    

    您可以创建一个 Response_class 控制器(类)并像我们上面那样调用它,否则您可以使用字符串代替

    public class Response_class{
        private String token_type;
        private String access_token;
        private String expires_in;
    
        public Response_class(String token_type, String access_token, String expires_in) {
            this.token_type = token_type;
            this.access_token = access_token;
            this.expires_in = expires_in;
        }
    
        public Response_class() {
        }
    
        public String getToken_type() {
            return token_type;
        }
    
        public void setToken_type(String token_type) {
            this.token_type = token_type;
        }
    
        public String getAccess_token() {
            return access_token;
        }
    
        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }
    
        public String getExpires_in() {
            return expires_in;
        }
    
        public void setExpires_in(String expires_in) {
            this.expires_in = expires_in;
        }
    
    
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用WebClient:

      byte[] image = WebClient.create("locahost:80/image.jpg")
              .get()
              .accept(MediaType.IMAGE_JPEG)
              .retrieve()
              .bodyToMono(byte[].class)
              .block();
      

      【讨论】:

        猜你喜欢
        • 2016-11-05
        • 2018-08-22
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        相关资源
        最近更新 更多