Spring HTTP Client

前端 未结 3 981
我在风中等你
我在风中等你 2021-01-31 02:11

I am new to Spring and I need my Java app to connect to another API over HTTP (JSON, RESTful). Does the Spring Framework have anything like a JSON HTTP Rest Client? What do Spri

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 02:45

    I achieved what I needed with the following:

    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;
    
    public class RestClient {
    
      private String server = "http://localhost:3000";
      private RestTemplate rest;
      private HttpHeaders headers;
      private HttpStatus status;
    
      public RestClient() {
        this.rest = new RestTemplate();
        this.headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "*/*");
      }
    
      public String get(String uri) {
        HttpEntity requestEntity = new HttpEntity("", headers);
        ResponseEntity responseEntity = rest.exchange(server + uri, HttpMethod.GET, requestEntity, String.class);
        this.setStatus(responseEntity.getStatusCode());
        return responseEntity.getBody();
      }
    
      public String post(String uri, String json) {   
        HttpEntity requestEntity = new HttpEntity(json, headers);
        ResponseEntity responseEntity = rest.exchange(server + uri, HttpMethod.POST, requestEntity, String.class);
        this.setStatus(responseEntity.getStatusCode());
        return responseEntity.getBody();
      }
    
      public void put(String uri, String json) {
        HttpEntity requestEntity = new HttpEntity(json, headers);
        ResponseEntity responseEntity = rest.exchange(server + uri, HttpMethod.PUT, requestEntity, null);
        this.setStatus(responseEntity.getStatusCode());   
      }
    
      public void delete(String uri) {
        HttpEntity requestEntity = new HttpEntity("", headers);
        ResponseEntity responseEntity = rest.exchange(server + uri, HttpMethod.DELETE, requestEntity, null);
        this.setStatus(responseEntity.getStatusCode());
      }
    
      public HttpStatus getStatus() {
        return status;
      }
    
      public void setStatus(HttpStatus status) {
        this.status = status;
      } 
    }
    

提交回复
热议问题