programing

스프링 HTTP 클라이언트

starjava 2023. 10. 24. 20:03
반응형

스프링 HTTP 클라이언트

저는 Spring을 처음 접했고 HTTP(JSON, RESTful)를 통해 다른 API에 연결하기 위해 Java 앱이 필요합니다.스프링 프레임워크에 JSON HTTP Rest Client와 같은 것이 있습니까?스프링 개발자들은 주로 무엇을 사용합니까?

저는 다음과 같이 제가 필요로 하는 것을 달성했습니다.

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;
  } 
}

가장 간단한 방법은RestTemplate, 공식 블로그에서 이 기사를 확인해 보십시오.

RestTemplate는 클라이언트 측 HTTP 액세스를 위한 중앙 Spring 클래스입니다.

GET의 예는 다음과 같습니다.

String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");

나는 다음과 같은 방법으로 그것을 했습니다.

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) {
        }
    }

}

언급URL : https://stackoverflow.com/questions/22338176/spring-http-client

반응형