Spring HTTP Client

前端 未结 3 982
我在风中等你
我在风中等你 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:28

    The simplest is to use the RestTemplate, check this article on the official Spring blog:

    The RestTemplate is the central Spring class for client-side HTTP access.

    This is an example of a GET:

    String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
    
    0 讨论(0)
  • 2021-01-31 02:42

    i did it in following way :

    import java.io.FileReader;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.converter.StringHttpMessageConverter;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    public class PostRequestMain {
    
        /**
         * POST with Headers call using Spring RestTemplate
         * 
         * 
         * @param args
         */
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
            Map map = new HashMap<String, String>();
            map.put("Content-Type", "application/json");
            headers.setAll(map);
            Map req_payload = new HashMap();
            req_payload.put("name", "piyush");
    
            HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
            String url = "http://localhost:8080/portal-name/module-name/";
    
            // Create a new RestTemplate instance
            RestTemplate restTemplate = new RestTemplate();
    
            // Add the String message converter
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    
    
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
    
    
            System.out.println(response);
    
        }
    
        private static void getPayloadMap() {
            JSONParser parser = new JSONParser();
    
            try {
    
                Object obj = parser.parse(new FileReader("C:\\Piyush\\test.json"));
                JSONObject jsonObject = (JSONObject) obj;
    
                Map payLoadMap = new HashMap();
                payLoadMap.putAll(jsonObject);
    
                System.out.println(jsonObject);
            } catch (Exception e) {
            }
        }
    
    }
    
    0 讨论(0)
  • 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<String> requestEntity = new HttpEntity<String>("", headers);
        ResponseEntity<String> 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<String> requestEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<String> 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<String> requestEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.PUT, requestEntity, null);
        this.setStatus(responseEntity.getStatusCode());   
      }
    
      public void delete(String uri) {
        HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
        ResponseEntity<String> 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;
      } 
    }
    
    0 讨论(0)
提交回复
热议问题