Spring RestTemplate 给出“500”错误,但 URL 相同,凭证在 RestClient 和 Curl 中有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11178937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:11:43  来源:igfitidea点击:

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

spring

提问by Kathir

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.

一个 Url,Credentials 在 RestClient UI 以及 Curl 中工作,因为当我通过 Spring RestTemplate 访问时出现“500”错误。

I am using the following code:

我正在使用以下代码:

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", user);
map.add("password", password);
restTemplate.postForObject(url, request, Employee.class, map);

Please let me know your suggestions or comments to fix the problem.

请让我知道您对解决问题的建议或意见。

采纳答案by Kathir

Below works fine

下面工作正常

For Post:

对于邮政:

restTemplate.postForObject(url, parametersMap, Employee.class);

restTemplate.postForObject(url, parametersMap, Employee.class);

url is : String - rest api URL parametersMap - MultiValueMap Employee - object which needs to be converted from the JSON response

url is : String - rest api URL parametersMap - MultiValueMap Employee - 需要从 JSON 响应转换的对象

回答by Youness

I would suggest to create your HttpComponentsClientHttpRequestFactoryand pass it to your RestTemplateas described below:

我建议创建您的HttpComponentsClientHttpRequestFactory并将其传递给您RestTemplate,如下所述:

ClientHttpRequestFactory requestFactory = new     
      HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());

RestTemplate restTemplate = new RestTemplate(requestFactory);

By this way, you would avoid server-side issues (like facing error code 500) when testing your application.

通过这种方式,您可以在测试应用程序时避免服务器端问题(例如面临错误代码 500)。

I had the same issue that worked in my local environment and not on the server.

我有同样的问题,在我的本地环境中而不是在服务器上。

It is a good practice to pass HttpClients.createDefault()to your HttpComponentsClientHttpRequestFactorywhile constructing it since by default, this factory uses system properties to create HttpClientfor your factory and that may cause lots of pain in real server environment. You may also pass your custom HttpClient.

在构建它时传递HttpClients.createDefault()给你是一个很好的做法,HttpComponentsClientHttpRequestFactory因为默认情况下,这个工厂使用系统属性HttpClient为你的工厂创建,这可能会在真实的服务器环境中造成很多痛苦。您也可以通过您的自定义HttpClient.

回答by webmadeup

RestTemplate header Accept problem 
--> accept - text/plain, application/json, */*

HttpClient 4.x header Accept
--> accept - application/json

so i fixed

所以我修好了

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);

http://www.manning-sandbox.com/message.jspa?messageID=119733

http://www.manning-sandbox.com/message.jspa?messageID=119733

回答by iOS-Developer84

I have also faced a situation where server response was "500 Internal server error"

我也遇到过服务器响应为“500 Internal server error”的情况

Though I have received success response from Postmanfor the same parameter value. So the problem was not in server side.

虽然我收到了Postman对相同参数值的成功响应。所以问题不在服务器端。

The problem was typo in parameter name, mismatch spelling between application parameter and server parameter

问题是参数名称拼写错误,应用程序参数和服务器参数之间的拼写不匹配

Server parameter        -> requestLabel
Application parameter   -> requestLable

Hope someone new like me get help from this.

希望像我这样的新人能从中得到帮助。

回答by Illidan

This may happen if your data contract class is missing default constructor - so Hymanson fails to construct it. You can try solve this issue by adding a privatedefault constructor to your class (despite it is private, Hymanson will be able to construct your class instance).

如果您的数据合同类缺少默认构造函数,则可能会发生这种情况 - 因此 Hymanson 无法构造它。您可以尝试通过向您的类添加私有默认构造函数来解决此问题(尽管它是私有的,但 Hymanson 将能够构建您的类实例)。

回答by valijon

You are passing name and password as uri variable:

您将名称和密码作为 uri 变量传递:

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

                          throws RestClientException

docs.spring.io

文档.spring.io

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

如果您有一些 url,如: http://yourhost:8080/dosomethingwithemployee/name/password并且您从 url 本身提取了名称和密码,那么它可能会起作用。

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<String, String> 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> T post(String url, Object requestObject, MultiValueMap<String, String> headers, Class<T> responseType) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

        HttpEntity request = new HttpEntity(requestObject, headers);
        T responseObject = restTemplate.postForObject(url, request, responseType);

        return responseObject;
    }

回答by Govind Ostwal

Though its too late to answer, below solution will help someone if above solutions did not work. For me, the error was with Request object and its header. Your request object should generate JSON as required by api. It should not have any extra field or additional getter method. In my case, I had additional getter method which was adding unnecessary field to request

尽管回答为时已晚,但如果上述解决方案不起作用,以下解决方案将对某人有所帮助。对我来说,错误在于 Request 对象及其标头。您的请求对象应根据 api 的要求生成 JSON。它不应该有任何额外的字段或额外的 getter 方法。就我而言,我有额外的 getter 方法,它添加了不必要的字段来请求

postForEntity = restTemplate.postForEntity(uri,entity,String.class);