Sending a key and file using MultipartEntityBuilder - java

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");

Related

POST a txt file to remote HTTP server

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

500 Internal server error Android HttpPost file upload

Lately I've noticed I get this error when I try to upload an image to my server using HttpPost, the code I use in Eclipse is this:
HttpPost httpPost = new HttpPost((String) params[0]);
Uri uri = (Uri) params[2];
String fileName = getFileName(uri);
if (fileName == null) fileName = "image";
InputStream inputStream = getContentResolver().openInputStream(uri);
HttpEntity mpEntity = MultipartEntityBuilder.create().addPart("place", new StringBody((String) params[3])).addBinaryBody("appuploadfile", inputStream, ContentType.create("image"), fileName).build();
httpPost.setEntity(mpEntity);
httpPost.setHeader("User-Agent", userAgent);
httpPost.setHeader("Cookie", cookie);
httpResponse = httpclient.execute(httpPost);
inputStream.close();
My host is using LiteSpeed and it has worked until now but they probably updated something so my code is not compatible anymore? If I change the server to my local one on my PC it works perfectly, I only get the error with my host. Does anybody know what could be wrong? I did try to packet sniff my app to see what it is sending exactly, and comparing it with the browser (firefox) the data looks a bit different and seems to be sent differently (note that the file upload works fine from a browser, it just doesn't work anymore from my android app).
This is how it looks like when it is sent from my app:
http://justpaste.it/mi11
This is how it looks like when it is sent from a browser (firefox, and it works fine):
http://justpaste.it/mi1c
Thanks!
HTTP error 500 means Internal Server Error. That is, the error is in the server, not in your application. You need to check the server's logs to see what caused it and fix it there.

POST request to server using java URLConnnection with params and file inputs

POST request to server using java URLConnnection
I need to send a POST request with the two parameters below:
param1=value1
param2=value2
And also I need to send a file.
In the case of Apache these 2 two(sending params and file) things are handled like below
post.setQueryString(queryString) // queryString is url encoded for eg: param1=value1&param2=value2
post.setRequestEntity(entity) // entity is constructed using file input stream with corresponding format
Please let me know if you have anything related to this problem.
Please note: When I try using Google Chrome REST client plug-in, I am getting the response as below (tried with all request content-types)
UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.
Try this API from Apache to send request internally with POST method.
The below is the sample Code to use API
List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
HttpPost postMethod = new HttpPost("http://yoururl/ProjectName");
list.add(new BasicNameValuePair("param1", "param1 Value")) ;
postMethod.setEntity(new UrlEncodedFormEntity(list));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();

Read file of content-disposition with java

I am developing a web-app that needs to query an ontology through a REST-API.
If I call the API through the browser, it opens a pop-up "Save As" through which I can save the file.
This is because the header of the response contains:
Content-Disposition: attachment; filename = query-result.srx
The problem is that I would like to receive the file within my web-app without using the browser.
The web-app is write on java and I use Apache HttpClient for send and receive, HTTP request and response:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
If I try to get the entity's content:
httpResponse.getEntity().getContent()
It return a useless value.
It 's something that you can do with this library, or should I use another library.
I found another question similar to mine but no one answered.
java-javascript-read-content-disposition-file-content
Thanks to all who answer me!
I realized that the error was in the query that I used the REST API. So the operations I did in Java were correct. With the command
httpResponse.getEntity().getContent()
you can take the content that is returned even if this file is described in the content-disposition.
Thanks to #Julian Reschke

Downloading a file using a REST POST call in java

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

Categories

Resources