RestTemplate post method is not working with exchange method.




Asked on July 13, 2017

I'm using spring boot microservice project. I have a rest api POST call that I need to send the body using raw, and I need to pass headers as follows: Authorization bearer 'token' Content-Type application/json. Working properly with postman.But when I try to call this from Java side I'm getting a 400 bad request exception.

I am getting the following exception:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
**org.springframework.web.client.HttpClientErrorException: 400 null**] with root cause

org.springframework.web.client.HttpClientErrorException: 400 null

However it worked in postman :

postman screenshot

Below is what I tried in Java.

String url = "http://localhost:8086/uaa/Groups/b8b135a7-4f20-4375-ad04-8bc140ba544e/members";
String token = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiIwYTY4OGJiMzNlMjQ0NzE2YWU1Mzk1ZWEzZmJiODQ5ZSIsInN1YiI6IjBkZTZlZDhkLWU1OGMtNGExNC1iNTdmLWM5Mjk2Y2JlYjM3NSIsInNjb3BlIjpbImFwaXMucmVhZCIsIm9wZW5pZCIsImFwaXMud3JpdGUiLCJ1YWEuYWRtaW4iLCJzY2ltLndyaXRlIiwic2NpbS5yZWFkIiwidWFhLnVzZXIiXSwiY2xpZW50X2lkIjoiY2xpZW50IiwiY2lkIjoiY2xpZW50IiwiYXpwIjoiY2xpZW50IiwiZ3JhbnRfdHlwZSI6ImF1dGhvcml6YXRpb25fY29kZSIsInVzZXJfaWQiOiIwZGU2ZWQ4ZC1lNThjLTRhMTQtYjU3Zi1jOTI5NmNiZWIzNzUiLCJvcmlnaW4iOiJ1YWEiLCJ1c2VyX25hbWUiOiJtYXJpc3NhIiwiZW1haWwiOiJtYXJpc3NhQHRlc3Qub3JnIiwiYXV0aF90aW1lIjoxNDk5NzU3NDc1LCJyZXZfc2lnIjoiMWE5MzYzNWYiLCJpYXQiOjE0OTk3NTc0NzUsImV4cCI6MTQ5OTgwMDY3NSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsInppZCI6InVhYSIsImF1ZCI6WyJzY2ltIiwiYXBpcyIsInVhYSIsIm9wZW5pZCIsImNsaWVudCJdfQ.OFUHQZ0I95na7VIZHQ-_JJlU6BQLkGLsV8TKk9lsPwA";
String origin = "uaa";
String type = "USER";
String value = "741db1c3-167f-401d-93a0-11d9cfca6281";
HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+token);

MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add("origin", origin);
postParams.add("type", type);
postParams.add("value", value);
System.out.println("Post parameters are"+postParams);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParams, headers);
System.out.println("request entities  are"+requestEntity);

ResponseEntity<Groups> result = restTemplate.exchange("http://localhost:8086/uaa/Groups/b8b135a7-4f20-4375-ad04-8bc140ba544e/members", HttpMethod.POST, requestEntity, Groups.class); 

return "added";

How do I fix this?

Thanks Regards,

Shilpa




Replied on July 14, 2017
The error "org.springframework.web.client.HttpClientErrorException: 400 null"
is because wrong headers or wrong request body. Header looks OK but there may be the problem in sending request body part. In your code request body is MultiValueMap.

MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add("origin", origin);
postParams.add("type", type);
postParams.add("value", value);

What is your server side code for the POST operation to accept the request body?

The solution of your problem could be that 
The request body should be an entity. Find the sample example.

Client Code:

    public void addArticleDemo() {
    HttpHeaders headers = new HttpHeaders();
   
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
   
        RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user/article";

Article objArticle = new Article();
objArticle.setTitle("Spring REST Security using Hibernate2");
objArticle.setCategory("Spring");

        HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers);

        ResponseEntity<String> uri = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        System.out.println(uri.getBody());    
    }


Server Code:


@PostMapping("article")
public ResponseEntity<Void> addArticle(@RequestBody Article article, UriComponentsBuilder builder) {
        boolean flag = articleService.addArticle(article);
        if (flag == false) {
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}






Replied on July 16, 2017
Thank you for the solution. This is worked.


Replied on July 16, 2017
Is there any other way other than using request body should be an entity?


Replied on July 16, 2017
What we can send to server as request body, depends on server side REST service method. In spring, @RequestBody in server side service method decides what can a client post.

For example, we have server side code.

@PostMapping("article")
public ResponseEntity<Void> addArticle(@RequestBody Article article) {
}

According to above code a client can post Article instance.  We can pass any datatype with @RequestBody.





Replied on July 16, 2017
Thank you.


Replied on November 26, 2017
follwing error is coming. Please help me anyone.

RestClient.java
package com.concretepage.client;

import java.net.URI;
import java.util.Arrays;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.concretepage.entity.Article;

public class RestClientUtil {
    public void getArticleByIdDemo() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/user/article/{id}";
        HttpEntity requestEntity = new HttpEntity(headers);
        ResponseEntity
responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article.class, 1);
        Article article = responseEntity.getBody();
        System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle()
                 +", Category:"+article.getCategory());      
    }
public void getAllArticlesDemo() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/user/articles";
        HttpEntity requestEntity = new HttpEntity(headers);
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article[].class);
        Article[] articles = responseEntity.getBody();
        for(Article article : articles) {
              System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle()
                      +", Category: "+article.getCategory());
        }
    }
    public void addArticleDemo() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/user/article";
    Article objArticle = new Article();
    objArticle.setTitle("Spring REST Security using Hibernate");
    objArticle.setCategory("Spring");
        HttpEntity
requestEntity = new HttpEntity
(objArticle, headers);
        URI uri = restTemplate.postForLocation(url, requestEntity);
        System.out.println(uri.getPath());   
    }
    public void updateArticleDemo() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/user/article";
    Article objArticle = new Article();
    objArticle.setArticleId(1);
    objArticle.setTitle("Update:Java Concurrency");
    objArticle.setCategory("Java");
        HttpEntity
requestEntity = new HttpEntity
(objArticle, headers);
        restTemplate.put(url, requestEntity);
    }
    public void deleteArticleDemo() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/user/article/{id}";
        HttpEntity
requestEntity = new HttpEntity
(headers);
        restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Void.class, 4);        
    }
    public static void main(String args[]) {
    RestClientUtil util = new RestClientUtil();
        //util.getArticleByIdDemo();
    util.getAllArticlesDemo();
    //util.addArticleDemo();
    //util.updateArticleDemo();
    //util.deleteArticleDemo();
    }    
}


Error


11:58:56.537 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/user/articles"
11:58:56.553 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
11:58:56.569 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/user/articles" resulted in 404 (Not Found); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 404 Not Found
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
at com.concretepage.client.RestClientUtil.getAllArticlesDemo(RestClientUtil.java:34)
at com.concretepage.client.RestClientUtil.main(RestClientUtil.java:76)




Replied on November 26, 2017
You need to check if your URL
http://localhost:8080/user/articles
is correct?
Are you using Spring Boot? if not then append application context of your application in your URL, Suppose if application context is spring-app, then URL will be 

http://localhost:8080/spring-app/user/articles





Replied on November 27, 2017
Thanks a lot for the quick response.I am very much new to this.

I am using springboot and url is fine. 
i am still seeing the same error



Replied on November 27, 2017
Look into the error stack trace

GET request for "http://localhost:8080/user/articles" resulted in 404 (Not Found);
 
It means URL is not correct. You can hit the URL
http://localhost:8080/user/articles
directly in browser to check if it is working. 



Replied on April 26, 2019
### Test Client
public void getAllArticleDemo() {
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
RestTemplate rest = new RestTemplate();
String url = "http://localhost:8080/user/article";
HttpEntity<String> requestEntity = new HttpEntity<String>(header);
ResponseEntity<Article[]> responseEntity = rest.exchange(url, HttpMethod.GET, requestEntity, Article[].class);
Article[] article = responseEntity.getBody();
System.out.println(Arrays.toString(article));
}

### Article Controller
@GetMapping("article")
public ResponseEntity<List<Article>> getAllArticles(){
List<Article> list = service.getAllArticle();
return new ResponseEntity<List<Article>>(list,HttpStatus.OK);
}

Console
JRE Oracle Corporation/12.0.1 is not supported, advanced source lookup disabled.
00:39:04.270 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/user/article"
00:39:04.855 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
00:39:05.000 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/user/article" resulted in 404 (null); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 404 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
at com.unicobib.client.RestClientUtil.getAllArticleDemo(RestClientUtil.java:35)
at com.unicobib.client.RestClientUtil.main(RestClientUtil.java:78)



Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us