I need to make POST request with body like this:
{"a":[12345]}
If I try to build POST requests like this:
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("{\"u\":[123]}", ""));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
it, of course, makes a POST request body with a "=" delimeter
{"a":[12345]}=
How do I make it right?
Try using StringEntity, created with your JSON payload, instead of your current use of UrlEncodedFormEntity, NameValuePair et al.
Related
We have some old java code that POSTs some fields and values to a dotnet5 web api - The api is having problems dealing with the body of the POST as it includes the url/uri as the first part of the body.
The Java sends: http://127.0.0.1:5555?producerRef=GREEN&systemId=78&status=false
But the api is expecting something like: producerRef=GREEN&systemId=78&status=false
as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example. If we send a test message via Postman then the api has no problems.
This is the Java code:
List<NameValuePair> params = new ArrayList<NameValuePair>(queryParams.size());
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// the address is just that, there's NO parameters
HttpPost post = new HttpPost(this.cmAddress.toURI());
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
It's quite simple, but always adds the url to the start of the body of the request. If this is the only way to produce this, what could I do to produce something that looks like this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example
Many Thanks.
This request seems like a GET request rather than a POST since the request params are in the URL. i don't know about the specifications of the Api you're using, but you can try OKHTTP, you can easily copy the code directly from postman
Postman Get example:
Your issue seems to be at below line
HttpPost post = new HttpPost(this.cmAddress.toURI());
This is the only place which will set the POST url ( another way is to use setURI which is not called anywhere in the code sample you have shared).
If you can use a debugger try checking the value of cmAdress variable
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");
In my program i am also got this error and found that the link not accepting repeated values.
so please check your link It may not accept any repeated parameters which is already available in that link.
I have a file that I want to upload so I have your standard MultipartEntityBuilder like this:
MultipartEntityBuilder multiPartEntity = MultipartEntityBuilder.create();
multiPartEntity.addBinaryBody("file", file);
I also have some form params that I send with the POST like this:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userId",userId));
postParameters.add(new BasicNameValuePair("taskId",taskId));
new UrlEncodedFormEntity(postParameters)
Both work individually, My question how do I do both in one call? I need to fold one into the other so I can make this in one HttpPost() call.
You seem to be confusing the application/x-www-form-urlencoded and multipart/form-data content types. When sending a multipart request, you are using multipart/form-data, in which case you don't need to URL encode the content. Just set the text directly
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file);
multipartEntityBuilder.addTextBody("userId", "someIdWith#url$encodable<>characters");
See the specification for more details.
I have an endpoint that requires an 'authenticity_token' that is in the format like:
Iq2rNXN+OxERv+s6TSloJfKkPZVvqnWe1m0NfODB5OI=
However, sometimes it has "special" characters, such as:
E7IzeP73OgPGgXM/up295ky1mMQMio2Nb8HMLxJFyfw=
This gets encoded to:
E7IzeP73OgPGgXM%26%2347%3Bup295ky1mMQMio2Nb8HMLxJFyfw%3D
For some reason, the endpoint does not like the encoding of those special characters and will think the token is invalid. Is it possible to add a POST variable that does not encode specific values? I am currently doing something like:
HttpPost post = new HttpPost(URL + NEW_FINDING);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("foo", foo));
nvps.add(new BasicNameValuePair("authenticity_token", authenticityToken));
post.setEntity(new UrlEncodedFormEntity(nvps));
You can always use ByteArrayEntity or StringEntity instead of UrlEncodedFormEntity and do the encoding yourself. It should look something like foo=var1&bar=var2.
You have to set Content-Type=application/x-www-form-urlencoded
You may want to find out what your endpoint expects as a charset parameter for the application/x-www-form-urlencoded value of the Content-Type header. Then pass it as a parameter to the UrlEncodedFormEntity constructor. This should be the right fix.
This is roughly the code I'm working with now:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", json.toString()));
nameValuePairs.add(new BasicNameValuePair("blob", file.getAbsolutePath()));
post_request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
The the reply I get back from the server is good for the first add() statement but, for the second one I'm not trying to send the path, I'm trying to send the file. Taking off .getAbsolutePath() should do the trick, but It won't let me as it only accepts strings. How would I go about sending the file?
you should use a MultipartEntity, not an UrlEncodedForm one. In a Multipart body you can store objects of different mime types