简体   繁体   English

org.springframework.web.client.HttpClientErrorException:RestTemplate 中的 400 错误请求

[英]org.springframework.web.client.HttpClientErrorException: 400 Bad Request in RestTemplate

I'm using Rest Template to POST data json, When i test o Postmen, it run success and return 200.我正在使用 Rest 模板发布数据 json,当我测试 o Postmen 时,它运行成功并返回 200。

This is my format json:这是我的格式 json:

{
"senderUser": "user@gmail.com",
"data": [
{
  "actionType": "update-contact",
  "data": {
  "name": "luong van",
  "lastname": "khanh",
  "type": 0,
  "title": "",
  "passport": "",
  "gender": 1,
  "bgInfo": "",
  "dateOfBirth": "",
  "emails": [{"value": "user@gmail.com"}],
  "phones": [{"value": "0902032618"}],
  "addresses": [{"street": "10", "city":"Osaka", "state": "Osake", "country":       
    {"code":"JP", "name":"Japan"}}],
  "tag": ""
 }
 }
]
}

this is my source:这是我的来源:

public static void main(String []args) {

    RestTemplate restTemplate = new RestTemplate();
    
    MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    
    restTemplate.getMessageConverters().add(jsonHttpMessageConverter);

    String url = "https://myservice.com/listeners/60011cbd4a674458d3b26025/90336429462601e7f3326641898fabd9948b349d";

    try {
        System.out.println("hi there");

        JSONArray json = new JSONArray();
        JSONObject obj = new JSONObject();

        obj.put("name", "khanh");
        obj.put("lastname", "luong van");
        obj.put("type", "0");
        obj.put("dateOfBirth", "");
        obj.put("emails", "user@gmail.com");
        obj.put("phones", "0902032618");
        obj.put("addresses", "Osaka");

        json.put(obj);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);         
        String result = restTemplate.postForObject(url, entity, String.class);          
        System.out.println(result);
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

this is exception when build log:这是构建日志时的异常:

17:07:58.483 [main] DEBUG org.springframework.web.client.RestTemplate - Created POST request for "https://myservice.com/listeners/60011cbd4a674458d3b26025/90336429462601e7f3326641898fabd9948b349d"
17:07:58.485 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/json, application/*+json, application/*+json, */*]
17:07:58.486 [main] DEBUG org.springframework.web.client.RestTemplate - Writing [{"emails":"user@gmail.com","addresses":"Osaka","name":"khanh","phones":"0902032618","dateOfBirth":"","type":"0","lastname":"luong van"}] as "application/json" using [org.springframework.http.converter.StringHttpMessageConverter@3a7442c7]
17:07:58.831 [main] DEBUG org.springframework.web.client.RestTemplate - POST request for "https://myservice.com/listeners/60011cbd4a674458d3b26025/90336429462601e7f3326641898fabd9948b349d" resulted in 400 (Bad Request); invoking error handler
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:380)
at com.javainuse.TestConnect.main(TestConnect.java:56)

I have try with a lot way but it still happen same error, How i can fix the problem?我尝试了很多方法,但仍然发生同样的错误,我该如何解决这个问题? many thank多谢

I think the BAD REQUEST is the correct answer in this case.我认为 BAD REQUEST 在这种情况下是正确的答案。 In your test using Postman, you passed the request body:在您使用 Postman 的测试中,您通过了请求正文:

{
    "senderUser": "user@gmail.com",
    "data": [{
        "actionType": "update-contact",
        "data": {
            "name": "luong van",
            "lastname": "khanh",
            "type": 0,
            "title": "",
            "passport": "",
            "gender": 1,
            "bgInfo": "",
            "dateOfBirth": "",
            "emails": [{
                "value": "user@gmail.com"
            }],
            "phones": [{
                "value": "0902032618"
            }],
            "addresses": [{
                "street": "10",
                "city": "Osaka",
                "state": "Osake",
                "country": {
                    "code": "JP",
                    "name": "Japan"
                }
            }],
            "tag": ""
        }
    }]
}

while your application log says you are sending the request body:当您的应用程序日志显示您正在发送请求正文时:

{
    "emails": "user@gmail.com",
    "addresses": "Osaka",
    "name": "khanh",
    "phones": "0902032618",
    "dateOfBirth": "",
    "type": "0",
    "lastname": "luong van"
}

Unless the service you are trying to consume is generic enough to accept too distinct request bodies, it will trigger a Bad Request response.除非您尝试使用的服务足够通用以接受太不同的请求主体,否则它将触发错误请求响应。

I recommend you to pass the Postman's request body as a parameter to the HTTPEntity constructor as a test:我建议您将 Postman 的请求正文作为参数传递给 HTTPEntity 构造函数作为测试:

HttpEntity<String> entity = new HttpEntity<String>("{\r\n" + 
            "   \"senderUser\": \"user@gmail.com\",\r\n" + 
            "   \"data\": [{\r\n" + 
            "       \"actionType\": \"update-contact\",\r\n" + 
            "       \"data\": {\r\n" + 
            "           \"name\": \"luong van\",\r\n" + 
            "           \"lastname\": \"khanh\",\r\n" + 
            "           \"type\": 0,\r\n" + 
            "           \"title\": \"\",\r\n" + 
            "           \"passport\": \"\",\r\n" + 
            "           \"gender\": 1,\r\n" + 
            "           \"bgInfo\": \"\",\r\n" + 
            "           \"dateOfBirth\": \"\",\r\n" + 
            "           \"emails\": [{\r\n" + 
            "               \"value\": \"user@gmail.com\"\r\n" + 
            "           }],\r\n" + 
            "           \"phones\": [{\r\n" + 
            "               \"value\": \"0902032618\"\r\n" + 
            "           }],\r\n" + 
            "           \"addresses\": [{\r\n" + 
            "               \"street\": \"10\",\r\n" + 
            "               \"city\": \"Osaka\",\r\n" + 
            "               \"state\": \"Osake\",\r\n" + 
            "               \"country\": {\r\n" + 
            "                   \"code\": \"JP\",\r\n" + 
            "                   \"name\": \"Japan\"\r\n" + 
            "               }\r\n" + 
            "           }],\r\n" + 
            "           \"tag\": \"\"\r\n" + 
            "       }\r\n" + 
            "   }]\r\n" + 
            "}", headers);

Use a POJO that matches your JSON schema and Jacksonmapper or similar to save time.使用与您的 JSON 模式和 Jacksonmapper 或类似的 POJO 匹配以节省时间。 POJO to JSON and vice versa is not a problem that you need to really worry too much about IMO as there framework level functionalities and libraries built to solve this very problem. POJO 到 JSON 和反之亦然,这不是您需要真正担心 IMO 的问题,因为有框架级功能和库来解决这个问题。 Building it with a JSONArray and JSONObject is too verbose and human-error prone.使用 JSONArray 和 JSONObject 构建它过于冗长且容易出现人为错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RestTemplate.postForObject - 错误:org.springframework.web.client.HttpClientErrorException:400错误请求 - RestTemplate.postForObject - Error: org.springframework.web.client.HttpClientErrorException: 400 Bad Request org.springframework.web.client.HttpClientErrorException:400使用HttpEntity restTemplate.exchange的错误请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request using HttpEntity restTemplate.exchange org.springframework.web.client.HttpClientErrorException:400错误的请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request org.springframework.web.client.HttpClientErrorException$BadRequest: 400 错误请求 - org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request org.springframework.web.client.HttpClientErrorException: 400 错误的 PUT 请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request for PUT org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity - org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity 我收到错误 org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request - I am getting the Error org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request binance - org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request binance 我收到错误消息“ org.springframework.web.client.HttpClientErrorException $ BadRequest:400错误请求” - I'm getting error “org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request” 如何修复错误org.springframework.web.client.HttpClientErrorException: 400 null,当使用RestTemplate访问微服务时 - How to fix the error org.springframework.web.client.HttpClientErrorException: 400 null, when using RestTemplate to access Microservice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM