Resttemplate get with headers java

How to set an «Accept:» header on Spring RestTemplate request? Example Tutorial

RestTemplate is one of the most commonly used tools for REST service invocations. So one of the major problems you might have in this RestTemplate is that how to set an «Accept» header on Spring RestTemplate request. In the last article, I have shown you how to POST and Consume JSON using RestTemplate in a Spring Based Java application and In this tutorial, we will go through some important points on how to add headers to RestTemplate and fix the errors related to them.

How to sett HTTP headers using Spring RestTempalte?

In this article, I will teach you how to set headers on HTTP request using Spring REST Template

So let’s have a look at RestTemplate GET request with parameters and headers.

Here we are using the getForObject() to make the GET request. Below is an example of using the getForObject() method to fetch the user information as a JSON string.

//rest api url 
String url = "XXX rest api url";

//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();

//GET request
String json = restTemplate.getForObject(url, String.class);

//print the json response
System.out.println(json);

If you want to pass query parameters, you can use the URL appended with them or else you can add placeholders to the URL for query parameters.

//query parameters appended to the URL
String url = "https://google.com/search?q=java";

// or else you can use placeholders to the URL for query parameters.
String url = "https://google.com/search?q=";

//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();

//GET request
String jsonString = restTemplate.getForObject(url, String.class);

//print the json response
System.out.println(jsonString);
GET Request with parameters and headers.
In order to add custom request headers to HTTP request, you should use the generic exchange() method provided by the RestTemplate class. So let's have a method in there.
We propose using one of the exchange methods that accept HttpEntity and allow us to set HttpHeaders in this case (for example, Authorization, Accept, Content-Type, etc.). We can also set the HTTP method we want to utilize by utilizing one of the exchange methods.

RestTemplate restTemplate = new RestTemplate(); 
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity httpEntity = new HttpEntity<>("some body", headers);
restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);

In the above code segment, instead of setting headers by using dedicated methods, you can use the general set method.

headers.set("Accept", "application/json");
It's also possible to provide HttpEntity to method postForObject() as a request parameter, as seen in the following example.
 
HttpEntityString> entity = new HttpEntity<>("some body", headers); 
restTemplate.postForObject(url, entity, String.class);
Let's have an another example with how to make a custom request headers to HTTP GET request, you can use the generic exchange() method provided by the RestTemplate class.
//query parameters appended to the URL
String url = "https://google.com/search?q=java";

// or else you can use placeholders to the URL for query parameters.
String url = "https://google.com/search?q=";

//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();

//http headers
HttpHeaders headers = new HttpHeaders();

// set `Content-Type` and `Accept` headers
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// example of custom header
headers.set("X-Request-Source", "Desktop");

// build the request
HttpEntity request = new HttpEntity(headers);

// make an HTTP GET request with headers
ResponseEntityString> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
String.class,
1
);

// check response
if (response.getStatusCode() == HttpStatus.OK) System.out.println("Request Successful.");
System.out.println(response.getBody());
> else System.out.println("Request Failed");
System.out.println(response.getStatusCode());
>
So let's have a real world example of how to set an "Accept" header on Spring RestTemplate request. Here is the Spring request handling code.
@RequestMapping( 
value= "/uom_matrix_save_or_edit",
method = RequestMethod.POST,
produces="application/json"
)
public @ResponseBody ModelMap uomMatrixSaveOrEdit(
ModelMap model,
@RequestParam("parentId") String parentId
) model.addAttribute("attributeValues",parentId);
return model;
>
and below is the Java REST client.
public void post() MultiValueMap params = new LinkedMultiValueMap(); 
params.add("parentId", "parentId");
String result = rest.postForObject( url, params, String.class) ;
System.out.println(result);
>
This is working fine and get a JSON string from the server side. 
But need to clarify how to specify the Accept: header (ex- application/json, application/xml. ) and request method (ex- GET, POST, . ) when using the RestTemplate?
To answer this question, you can use one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders.(You can also sepecify the HTTP method you want to use).
 
RestTemplate restTemplate = new RestTemplate(); 
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntityString> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
You can pass the HttpEntity as a request argument to postForObject.
 
HttpEntityString> entity = new HttpEntity<>("body", headers); 
restTemplate.postForObject(url, entity, String.class);
The request parameter can be a HttpEntity in order to add additional HTTP headers to the requerst.
So in the above, we have discussed how to make GET request with non parameters and also with parameters and headers. The request parameter can be a HttpEntity in order to add additional HTTP request headers to the request. 
So in this tutorial, we discussed how to set an "Accept" header on Spring RestTemplate request with many examples. 
Hope you understand those and hope to see you in the next tutorial. Until then Bye. 

Thank you for reading this article so far. If you have any question or feedback or doubt, feel free to ask in comments.

Источник

RestTemplate GET Request with Parameters and Headers

In this article, you will learn how to make different HTTP GET requests using the RestTemplate class in a Spring Boot application.

To make a GET HTTP request, you can use either getForObject() or getForEntity() method. Here is an example that uses the getForObject() method to fetch the user information as a JSON string:

// request url String url = "https://jsonplaceholder.typicode.com/posts/1"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String json = restTemplate.getForObject(url, String.class); // print json System.out.println(json); 

To pass query parameters, you can append them directly to the URL or use placeholders. Here is an example of a GET request made with query parameters appended to the URL:

// request url String url = "https://google.com/search?q=java"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String html = restTemplate.getForObject(url, String.class); 
// request url String url = "https://google.com/search?q="; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String html = restTemplate.getForObject(url, String.class, "java"); 

To add custom request headers to an HTTP GET request, you should use the generic exchange() method provided by the RestTemplate class. The following GET request is made with query parameters and request headers:

// request url String url = "https://jsonplaceholder.typicode.com/posts/"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); // set `Content-Type` and `Accept` headers headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // example of custom header headers.set("X-Request-Source", "Desktop"); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityString> response = restTemplate.exchange( url, HttpMethod.GET, request, String.class, 1 ); // check response if (response.getStatusCode() == HttpStatus.OK)  System.out.println("Request Successful."); System.out.println(response.getBody()); > else  System.out.println("Request Failed"); System.out.println(response.getStatusCode()); > 
// request url String url = "https://jsonplaceholder.typicode.com/posts"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); // add basic authentication header headers.setBasicAuth("username", "password"); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityString> response = restTemplate.exchange( url, HttpMethod.GET, request, String.class ); // check response if (response.getStatusCode() == HttpStatus.OK)  System.out.println("Request Successful."); System.out.println(response.getBody()); > else  System.out.println("Request Failed"); System.out.println(response.getStatusCode()); > 

Using RestTemplate, you can also map the JSON response directly to a Java object. Let us first create a simple model class: Post.java

public class Post implements Serializable  private int userId; private int id; private String title; private String body; public Post()  > public Post(int userId, int id, String title, String body)  this.userId = userId; this.id = id; this.title = title; this.body = body; > // getters and setters, equals(), toString() . (omitted for brevity) > 
// request url String url = "https://jsonplaceholder.typicode.com/posts/1"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityPost> response = restTemplate.exchange( url, HttpMethod.GET, request, Post.class ); // check response if (response.getStatusCode() == HttpStatus.OK)  System.out.println("Request Successful."); System.out.println(response.getBody()); > else  System.out.println("Request Failed"); System.out.println(response.getStatusCode()); > 

Check out the Making HTTP Requests using RestTemplate in Spring Boot guide for more RestTemplate examples. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Kotlin перевод числа в строку
Оцените статью