Spring RestTemplate gives “500” error but same URL, credentails works in RestClient and Curl

后端 未结 7 1836
眼角桃花
眼角桃花 2020-12-30 03:06

An Url, Credentials works in RestClient UI as well as with Curl where as i\'m getting \"500\" error when access the same via Spring RestTemplate.

I am using the foll

7条回答
  •  感动是毒
    2020-12-30 03:30

    You are passing name and password as uri variable:

    public  T postForObject(java.lang.String url,
                                         @Nullable
                                         java.lang.Object request,
                                         java.lang.Class responseType,
                                         java.util.Map uriVariables)
    
                              throws RestClientException
    

    docs.spring.io

    If you had some url like: http://yourhost:8080/dosomethingwithemployee/name/password and you extracted name&password from url itself, then it probably would work.

    String url = "http://yourhost:8080/dosomethingwithemployee/{name}/{password}"
    restTemplate.postForObject(url, request, Employee.class, map);
    

    However, I think you have been trying to send name and password in request body:

    public SomeType getResponse(String login, String password) {
            MultiValueMap headers = new LinkedMultiValueMap<>();
            headers.add("Content-Type", "application/json");
            Employee employee = new Employee();
            employee.setName(login);
            employee.setPassword(password);
            SomeType responseBody = post("http://locahost:8080/dosomethingwithemployee", employee, headers, SomeType.class);
            return responseBody;
        }
    
        public  T post(String url, Object requestObject, MultiValueMap headers, Class responseType) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    
            HttpEntity request = new HttpEntity(requestObject, headers);
            T responseObject = restTemplate.postForObject(url, request, responseType);
    
            return responseObject;
        }
    

提交回复
热议问题