Java Applet HttpPost to apache via HttpClient/HttpPost and InputStreamBody - java

Program is an applet designed to take some files, process them, send them through a ZipOutputStream, and upload the (usually rather large) zip file to the server. It is using Apache HttpClient 4.2.1 (and ancillary libraries). My post request is executing in a privileged space. The issue I'm having is Apache/2.2.16 (Win32) refuses to take the request. I get an error in the Apache error logs, "chunked Transfer-Encoding forbidden".
If I use wireshark to capture the connection, the request looks like:
POST /data/FileUpload.php?userId=21 HTTP/1.1
Transfer-Encoding: chunked
Content-Type: multipart/form-data; boundary=PjgV56PRG1T0eeWZNfM3Gumc8v0p8j
Host: 192.168.2.16:8000
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
10be
--PjgV56PRG1T0eeWZNfM3Gumc8v0p8j
Content-Disposition: form-data; name="ZipFile"; filename="JavaUploaderZipStream.zip"
Content-Type: application/zip
Content-Transfer-Encoding: binary
The code that executes this request is:
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
ZipCompressionInputStream zipStream = new ZipCompressionInputStream(fileList);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
InputStreamBody uploadPart = new InputStreamBody(zipStream, "application/zip", "JavaUploaderZipStream.zip");
reqEntity.addPart("ZipFile", uploadPart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
EntityUtils.consume(responseEntity);
} finally {
httpPost.releaseConnection();
}
From what I can tell, Apache 2.2 is supposed to accept chunked data. I don't see any switches that reject it. It seems to be accepting the HTTP/1.1 connection. I'm at a loss as to why it just flat refuses anything I try.

Related

Error posting files with RequestBuilder, 403 Forbidden cloudflare

I'm trying to make a request to send an mp3 file via HttpUriRequest multipartRequest, I've added all the headers that the API documentation asks for (Content-Type multipart/form-data).
However, a strange thing I noticed was the "Host" header, when I make a request in Postman, it goes successfully, but when I request my implementation, I get the following error:
400 Bad Request - cloudflare
My code:
CloseableHttpClient httpclient = HttpClients.createDefault();
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitybuilder.addBinaryBody("file", new File("/C:/64551f6c78bc742885a2f0b8100cb039-
recording.mp3"));
HttpEntity mutiPartHttpEntity = entitybuilder.build();
RequestBuilder reqbuilder =
RequestBuilder.post("https://api.pipedrive.com/v1/callLogs/"+idActive+"/recordings?
api_token=a09e26295e89cb2ccc89b676358deae384046449");
reqbuilder.setEntity(mutiPartHttpEntity);
reqbuilder.addHeader("Content-Type", "multipart/form-data");
reqbuilder.addHeader("Accept", "*/*");
reqbuilder.addHeader("Accept-Encoding", "gzip, deflate, br");
reqbuilder.addHeader("Connection", "keep-alive");
reqbuilder.addHeader("Host", "http://localhost:8080/attach");
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();
multipartRequest.addHeader("Content-Type", "multipart/form-data");
HttpResponse httpresponse = httpclient.execute(multipartRequest);
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
System.out.println(httpresponse.getStatusLine());
If anyone has been through this, any help will be of great value.
You are adding the "multipart/form-data" after you already build your Request, move it up a line
I put this line up but I still get an error, there was a mistake, the part before building the RequestBuilder reqbuilder I already added all the headers

apache cxf MultiPart request has no Content-Length header

I'm having below code to send a multipart/form-data request.
List<Attachment> multipartData = new ArrayList<>();
ContentDisposition cd1 = new ContentDisposition("form-data; name=\"file\";
filename="+fileObj.getName());
FileInputStream inputStream = new FileInputStream(fileObj);
multipartData.add(new Attachment("file",inputStream, cd1));
MultipartBody multipart = new MultipartBody(multipartData);
In my RestClient class, I'm using the below lines of code to send a POST request using JAX-RS Client object
if ("POST".equals(method)) {
response = this.client.getBuilder().post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
I checked the HTTP request body using Wiremock and is as below:
Transfer-Encoding: [chunked]
Accept: [*/*]
Cache-Control: [no-cache]
User-Agent: [Apache-CXF/3.2.5]
Connection: [keep-alive]
Host: [127.0.0.1:9990]
Pragma: [no-cache]
Content-Type: [multipart/form-data; boundary="uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1"]
--uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <file>
Content-Disposition: form-data; name="file"; filename=sample.txt
<File content goes here>
I want to know how the content-length header is missing in the request payload. Is there any way to set the content-length header to the request?
Please help me.
I used the apache cxf WebClient to unset the transfer encoding as chunked.
if ("POST".equals(method)) {
Invocation.Builder builder = this.client.getBuilder();
WebClient.getConfig(builder).getHttpConduit().getClient().setAllowChunking(false);
response = builder.post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
}
With this, the client is able to send the request with content-length header.

HTTP/1.1 422 Unprocessable Entity Error when sending data to LoopBack from Java client

I am doing an HttpPost to send data to LoopBack and get the response. I am getting an error as below from LoopBack :
HTTP/1.1 422 Unprocessable Entity [X-Powered-By: Express, Vary: Origin, Accept-Encoding, Access-Control-Allow-Credentials: true, Content-Type: application/json; charset=utf-8, Content-Length: 1528, Date: Thu, 18 Dec 2014 18:13:45 GMT, Connection: keep-alive]
So, what I did in java is created a json from a java object , when I used this JSON in loopback api explorer, the data was inserted and gave me response 200, but doing from Java, I am getting this error. Does anyone have an idea about this.
Java code is as below
JSONObject json = new JSONObject(jsonString);
StringEntity stringEntity = new StringEntity(json.toString());
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(POST_CLAIM_URL);
post.setEntity(stringEntity);
HttpResponse httpResponse = null;
httpResponse = client.execute(post);
I had make sure , I am not adding a duplicate entry.
Regards,
Varun
For authentication, see this example https://github.com/strongloop/loopback-example-access-control.
As for the authentication token, you can set it in the query string of the request, like http://localhost:3000/api/your-model?access_token=TOKEN

Multipart JSON POST request

please read my post:
I need to post the image to the JSON WS with this parameters:
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: {number_of_bytes_in_entire_request_body} -- Check your rest client API's. Some would automatically determine content-length at runtime. Eg. jersey client api.
--foo_bar_baz
Content-Type: application/json;
{
"filename": "cloudx.jpg"
}
--foo_bar_baz
Content-Type: image/jpeg
{JPEG data}
--foo_bar_baz--
I'm building Android application and I need to write the request to send the image to the above WS. I was looking around for some time and I didn't found good resource to study this issue I have.
following may give you basic idea
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(<URI>);
HttpEntity entity = new FileEntity(file,ContentType.MULTIPART_FORM_DATA);
//there are other types of entities and content types too check documentation
req.setEntity(entity);
HttpResponse response = httpClient.execute(req);

Setting locale with DefaultHttpClient?

I'm using DefaultHttpClient to make an http connection. I [think] we can set the preferred locale in the http headers [http accept-language] when making a connection, which the server can check and send back content in a matching language (if it wants).
Anyone know if this is possible, or how to go about doing this with DefaultHttpClient?
Thanks
You have to add your header to HttpRequest object
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
request.addHeader("Accept-Language", "en");
HttpResponse response = client.execute(request);

Categories