问题描述:

I'm trying to do a request using a small Java program but I'm getting a 400 - Bad Request as response:

URI uri = new URIBuilder().setScheme("https")

.setHost("somehost.com")

.setPath("/API/v1/export").build();

HttpPost post = new HttpPost(uri);

post.setHeader("X-API-ID", "myId");

post.setHeader("Accept", "application/json");

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("format", "csv"));

params.add(new BasicNameValuePair("userId", "userId"));

post.setEntity(new UrlEncodedFormEntity(params));

JsonNode responseJson = sendResponseEngineRequest(post);

This responseJson returns the following value:

{"meta":{"httpStatus":"400 - Bad

Request","error":{"errorMessage":"Invalid Content-Type.

expected=application/json

found=application/x-www-form-urlencoded","errorCode":"RP_0.1"}}}

Thanks in advance.

网友答案:

The answer is literally in the error you're getting.

You specify you will only accept post.setHeader("Accept", "application/json"); and the error is telling you that what you're requesting is found=application/x-www-form-urlencoded

If you have control over the endpoint you're requesting data, change it to application/json. If you don't change post.setHeader("Accept", "application/json"); to post.setHeader("Accept", "application/x-www-form-urlencoded");

网友答案:

Since this is a POST request, you may need to provide both Accept and Content-Type headers.

Accept: What you are expecting to receive. Content-Type: What you are sending to server

post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
相关阅读:
Top