I am trying to upload a 260k image file as part of multipart form using Apache HttpAsyncClient library.
I create my form this way:
val multipartEntityBuilder = new MultipartEntityBuilder
multipartEntityBuilder.addBinaryBody("file", file)
val multipartEntity = multipartEntityBuilder.build()
And then I receive a ContentTooLongException when performing request basically because of this line in the library's source code:
https://github.com/apache/httpclient/blob/4.5.3/httpmime/src/main/java/org/apache/http/entity/mime/MultipartFormEntity.java#L102
I searched a lot, but didn't find any explanation why this limitation for contentLength is present in code. Maybe someone could explain it? And my second question: what is the proper way to make an upload request for a file larger than 25 kb?
Thanks!
Found the solution: create inputStream over file and wrap the multipart entity with BufferedHttpEntity and then pass this buffered entity to request:
val multipartEntityBuilder = MultipartEntityBuilder.create()
multipartEntityBuilder.addBinaryBody("file", new FileInputStream(file), ContentType.DEFAULT_BINARY, name)
val multipartEntity = multipartEntityBuilder.build()
val entity = new BufferedHttpEntity(multipartEntity)
Related
In Spring Boot the zip file that comes as a response has a corrupted structure before saving, but there is no problem when I save it physically. I need to take the file in the zip file and process the information in the database, but I cannot physically download this file because I am using GCP. How can I extract the file in this zip file that comes as a response?. How can I solve this please help.
Here is what it looks like in response.body() before saving (part of it):
"PK C`iUq �=n 緰) bu_customerfile_22110703_B001_10292121141�]i��������RI%U�v��CJ� ���×��My��y/ίϹ�������=>����}����8���}~}~yz�������ͲL��
�o�0�fV�29f�����6$K�c$�F��/�8˳�L��_�QaZ-q�F�d4γE�[���(f�8�D�0��2_��P"�I�A��D��4�߂�����D��(�T�$.��<�,���i]Fe�iM�q<ʨ�Olmi�(&���?�y�y4��<��Q�X�ޘp�#�6f-.F����8����"I㢨ҤU]�E��WI� %#������(W�8*0c�p:L��:� �}�G����e<����a�"
Here is the request call:
OkHttpClient client1 = new OkHttpClient().newBuilder()
.build();
MediaType mediaType1 = MediaType.parse("text/plain");
RequestBody body1 = RequestBody.create(mediaType1, "");
Request request1 = new Request.Builder()
.url(vers)
.method("POST", body1)
.addHeader("Cookie", "ASP.NET_SessionId=44dxexdxass5mtf00udjfwns")
.build();
Response response1 = client1.newCall(request1).execute();
String data = response1.body().string();
Would it be a matter of encoding type? String is of type UTF-16 (I think). Try a different datatype that is more like an array/vector of bytes.
Try something like what is mentioned here:
Having trouble reading http response into input stream
Update: Get the response as a stream of bytes and feed it into a ZipInputStream object as shown here https://zetcode.com/java/zipinputstream/#:~:text=ZipInputStream%20is%20a%20Java%20class,both%20compressed%20and%20uncompressed%20entries.
Then iterate over the contained files to find the one you need. Then retrieve the stream associated with the zipped file. Then you can read from there. (I realize that is a bit of handwaving, but it's been a while since I used Zip files and Java.) That should get you down the correct path.
I want to upload a file to an object storage minio which created a presigned URL using a Java client API.
In the documentation only refers to creating presigned URL or creating some. Is there a to upload using the presigned url.
I think you probably got the answer by now, gonna put it here for others who might have stumbled upon similar task.
There are a few different HTTP clients that you could use in JAVA, so implementations may vary. The idea is, once you get the URL, it is just a matter of sending an HTTP PUT request using the URL with the file's binary content, just like you would do in any file upload procedure. As far as I know, you cannot send multipart file data directly using PUT, you have to send binary stream.
Here's an example of uploading a jpeg file with OkHttpClient:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("image/jpeg");
RequestBody body = RequestBody.create(mediaType, "<file contents here>");
Request request = new Request.Builder()
.url("<minio presigned url here>")
.method("PUT", body)
.addHeader("Content-Type", "image/jpeg")
.build();
Response response = client.newCall(request).execute();
Another example with Spring's RestTemplate where the incoming request to the controller is a MultipartFile. If it's a File object instead, you can use your favorite utility method such as byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file) to get a byte array from that file.
HttpHeaders headers = new HttpHeaders();
HttpEntity<byte[]> entity = new HttpEntity<>(multipartFile.getBytes(), headers);
restTemplate.exchange(new URI("<presignedUrl>"),
org.springframework.http.HttpMethod.PUT, entity, Void.class);
You can search for your specific HTTP Client, just need to look for "RESTful file upload with PUT request" Or something similar.
I am a little lost with this problem and need some help with this. What I need to do is make a post request to an HTTP REST Interface using Java. In this request, I need to send the key as the parameter and need to upload the text file to the server. This file will be locally available.
Nothing here is user input. I am not sure how to upload file to that server In the instruction page this is written
This step requires an HTTP Post request to the URI "someurl.com"
With HTTP Post variable named key and its value
and the in.txt file attached
After making this request I will get an out.txt file as a response.
So far over the internet I found this code which is close
dos.writeBytes(message); //here message is String and dos is DataOutputStream
dos.flush();
dos.close();
But here message is the string, I was wondering if there is a way to sent file to the server.
You can use this method to upload file with some key and value parameters
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("someurl.com");
//Post variable named key and its value
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("id", id, ContentType.TEXT_PLAIN);
builder.addTextBody("apd", apd, ContentType.TEXT_PLAIN);
//path of file
String filepath = "C:\Users\Downloads\images\file.txt";
// This attaches the file to the POST:
File f = new File(filepath);
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Guys thank you for your answers but they didn't worked for me. I don't have much experience with API of this sort. In the help section, I found to use curl and was able to successfully get the results. Here is the code I used
String[] command = {"curl","-H","key:keyValue","-F","file=#in.txt",
"http://example.com/evaluate.php ","-o","output.txt"};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
p = process.start();
Yes in the massage parameter you need to Serialize your file - convert it to bytes, encrypt it. Then send it as a message. Then decrypt and build your file from the bytes on the other side
I don't have much experience with networking and my Googling skills don't seem to get me any further than this.
I need to send a file to a server with "file" being the HTTP POST key. Here is what I have:
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.addBinaryBody("file", image);//set up the object to send
HttpPut put = new HttpPut("http://address:port");
put.setEntity(mpEntity.build());//put the object to be sent
//try sending
try {
HttpResponse response = client.execute(put);
...
I'm getting a 404 error when I process the response using an InputStream. The server is up and running and works fine when I test it from the terminal.
Add the content type and the name of the file to the binary body like this:
mpEntity.addBinaryBody("file", image, ContentType.create("image/jpeg"), "image_name.jpg");
I have a REST service which returns a file when it is called via a POST call with an XML file as the parameter. My goal is to access the service using a client (a simple httppost call in a java class). So far, I am doing as below:
DefaultHttpClient defaultHtppclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("resturl");
StringEntity input = new StringEntity("input xml file ");
input.setContentType("application/xml");
postRequest.setEntity(input);
HttpResponse response = defaultHtppclient.execute(postRequest);
I am getting the contents of the file when I convert the response using :
String content = EntityUtils.toString(response.getEntity());
But I am struggling to download the file as such from the java class. When I trigger the URL in Firefox HTTP resource test. I am getting the headers as:
Content-Disposition: attachment; filename = filenameFromserver
Content-Type: application/octet-stream
Is there any way to download the file as such from the client ?
The call you're making is expecting application/xml, the server is sending you an octet-stream.
You'll have to read in the bytes it's sending you and write them out to the file that you want. I'd recommend searching around on how to read in an octet stream.
For an example take a look at this post:
Reading binary file from URLConnection