I am trying to call an api. Whenever i include 'é' in the request body getting 400 bad request. When i remvove 'é' everything works fine. below is my code and response.
CloseableHttpClient httpClient = (CloseableHttpClient) getHttpClient();
HttpPost httpPost = getHttpPost("xxx");
StringEntity entity = new StringEntity(request.toString());
entity.setChunked(false);
httpPost.addHeader("content-type", "application/json");
httpPost.setEntity(entity);
System.out.println("contentlength = "+String.valueOf(entity.getContentLength()));
CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
System.out.println("response = "
+ response);
StatusLine statusLine = response.getStatusLine();
System.out.println("statusLine = "
+ statusLine);
String responseEntity = EntityUtils.toString(response.getEntity());
System.out.println("responseEntity = "
+ responseEntity);
Response :
contentlength = 964 response = HttpResponseProxy{HTTP/1.1 400 Bad
Request [Content-Length: 0,Chunked: false]} statusLine = HTTP/1.1 400
Bad Request responseEntity =
StringEntity entity = new StringEntity(request.toString(),"UTF-8");
this solved the issue.
Set the content-type to:
"application/json;charset=UTF-8"
when sending the post request in the application you are using.
Related
I would like to send POST request using Java equivalent of the following CURL example:
echo "param value" | curl --data-binary #- -uuser:pass https://url
I've tried apache http setEntity(FileEntity entity), 400 bad request
I've tried apache http setEntity(MultiPartEntity entity), 400 bad request
// ----------------
// General part
String url = "https://url";
String content = "param" + " " + "value";
File file = new File("test.txt");
try {
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
String encoding = Base64.getEncoder().encodeToString(("user:pass").getBytes());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
// -----------------
// 1. FileEntity try
FileEntity reqEntity = new FileEntity (file, ContentType.DEFAULT_BINARY);
post.setEntity(reqEntity);
HttpResponse response = httpclient.execute(post);
// ----------------
// 2. Multipart try
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, org.apache.http.entity.ContentType.DEFAULT_BINARY);
mpEntity.addPart("userfile", cbFile);
post.setEntity(mpEntity);
HttpResponse response = httpclient.execute(post);
I've expected to get 200, but got 400 Bad request.
Original CURL works as expected
Problem with boundary parameter is not in the Content-Type header
Actually If you are using one of multipart/ content types, you are actually required to specify the boundary parameter in the Content-Type header ,But in here with curl request not trying generate any boundary values , without boundary values the server (in the case of an HTTP request) will not be able to parse the payload
I have a JSON body as Java String. I would like to convert this String to RestAssured Response. Is this possible?
Or
Is it possible to convert apache HttpResponse to RestAssured Response
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
I'd like to convert httpResponse to RestAssured Response
The Response Javadoc says "The response of a request made by REST Assured.". So, no I don't think its possible. I would make the request with RestAssurred anyway, I find it easier.
Reference: http://static.javadoc.io/com.jayway.restassured/rest-assured/1.2.3/com/jayway/restassured/response/Response.html
I need to post some form parameters to a server through an HTTP request (one of which is a file). So I use Apache HTTP Client like so...
HttpPost httpPost = new HttpPost(urlStr);
params = []
params.add(new BasicNameValuePair("username", "bond"));
params.add(new BasicNameValuePair("password", "vesper"));
params.add(new BasicNameValuePair("file", payload));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-type", "multipart/form-data");
CloseableHttpResponse response = httpclient.execute(httpPost);
The server returns an error, stack trace is..
the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:954)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
I understand from other posts that I need to somehow come up with a boundary, which is a string not found in the content. But how do I create this boundary in the code I have above? Should it be another parameter? Just a code sample is what I need.
As the exception says, you have not specified the "multipart boundary". This is a string that acts as a separator between the different parts in the request. But in you case it seems like you do not handle any different parts.
What you probably want to use is MultipartEntityBuilder so you don't have to worry about how it all works under the hood.
It should be Ok to do the following
HttpPost httpPost = new HttpPost(urlStr);
File payload = new File("/Users/CasinoRoyaleBank");
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("file", payload)
.addTextBody("username", "bond")
.addTextBody("password", "vesper")
.build();
httpPost.setEntity(entity);
However, here is a version that should be compatible with #AbuMariam findings below but without the use of deprecated methods/constructors.
File payload = new File("/Users/CasinoRoyaleBank");
ContentType plainAsciiContentType = ContentType.create("text/plain", Consts.ASCII);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(payload))
.addPart("username", new StringBody("bond", plainAsciiContentType))
.addPart("password", new StringBody("vesper", plainAsciiContentType))
.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
The UrlEncodedFormEntity is normally not used for multipart, and it defaults to content-type application/x-www-form-urlencoded
I accepted gustf's answer because it got rid of the exception I was having and so I thought I was on the right track, but it was not complete. The below is what I did to finally get it to work...
File payload = new File("/Users/CasinoRoyaleBank")
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(payload))
entity.addPart( "username", new StringBody("bond"))
entity.addPart( "password", new StringBody("vesper"))
httpPost.setEntity( entity );
CloseableHttpResponse response = httpclient.execute(httpPost);
I am using Apache HttpComponents v4.3.3 (maven httpclient and httpmime). I need to upload a file with some metadata. The curl command, which works, looks like the following.
curl -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=#somefile.zip;type=application/zip' https://www.some.domain/
I have tried mimicking this curl post as the following.
HttpEntity entity = MultiPartEntityBuilder
.create()
.addPart("field1",new StringBody("val1",ContentType.TEXT_PLAIN))
.addPart("field2",new StringBody("val2",ContentType.TEXT_PLAIN))
.addPart("file", new FileBody(new File("somefile.zip"), ContentType.create("application/zip"))
.build();
HttpPost post = new HttpPost("https://www.some.domain");
post.addHeader("Content-Type", "multipart/mixed");
However, after I use HttpClient to execute the HttpPost, I get the following exception (server code is also Java running on Jetty).
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
When I add a trace to curl
curl --trace - -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=#somefile.zip;type=application/zip' https://www.some.domain/
I see that the form field/value pairs are set as HTTP headers.
Content-Disposition: form-data; name=field1...value1
Any idea on what I'm doing wrong here? Any help is appreciated.
I tinkered a bit and did two things to get the code working.
no longer use addPart(...)
no longer set Content-Type header
Here's the revised snippet that's working in case anyone is interested.
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("field1","val1")
.addTextBody("field2","val2")
.addBinaryBody("file", new File("somefile.zip"),ContentType.create("application/zip"),"somefile.zip")
.build();
HttpPost post = new HttpPost("https://www.some.domain");
post.setEntity(entity);
I also set HttpComponents to debug mode.
-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG
It turns out that each part now has a boundary. Even better yet, the Content-Type and boundary are autogenerated.
Content-Type: multipart/form-data; boundary=5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc
Here my full code based in last response, but is slightly different, i had the same error but now works (thanks Jane!):
public String sendMyFile(String p_file, String p_dni, String p_born_date) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("http://localhost:2389/TESTME_WITH_NETCAT");
/* Campos del formulario del POST que queremos hacer */
File fileIN = new File(p_file);
/* Construimos la llamada */
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody ("p_file" , fileIN)
.addTextBody ("p_dni" , p_dni)
.addTextBody ("p_born_date" , p_born_date);
httppost.setEntity(reqEntity.build());
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
System.out.println("1 ----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("2 ----------------------------------------");
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("3 ----------------------------------------");
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
return "OK";
}
I need to encode the params to ISOLatin which i intend to post to the site. I'm using org.apache.http. libraries. My code looks like follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("www.foobar.bar");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
params.setParameter("action", "find");
params.setParameter("what", "somebody");
post.setParams(params);
HttpResponse response2 = httpClient.execute(post);
Thank you!
You are setting parameters wrong. Here is an example,
PostMethod method = new PostMethod(url);
method.addParameters("action", "find");
method.addParameters("what", "somebody");
int status = httpClient.executeMethod(method);
byte[] bytes = method.getResponseBody();
response = new String(bytes, "iso-8859-1");
if (status != HttpStatus.SC_OK)
throw new IOException("Status code: " + status + " Message: "
+ response);
The default encoding will be Latin-1.