Spring HTTP Client

JavaSpring

Java Problem Overview


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 Spring developers usually use?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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");

Solution 3 - Java

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcelorocksView Question on Stackoverflow
Solution 1 - JavamarcelorocksView Answer on Stackoverflow
Solution 2 - JavaAngular UniversityView Answer on Stackoverflow
Solution 3 - JavaPiyush MittalView Answer on Stackoverflow