Downloading a file using a REST POST call in java - 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

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

Sending a key and file using MultipartEntityBuilder

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

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

Download a PDF file via REST service with “Content-Disposition” Header in java

I am trying to download a PDF file from a response of Java REST call after custom authentication check.
I can see downloaded file but it is empty file.
Below is my code snippet.
//Custom HTTPClient
HTTPAuthClient client = new HTTPAuthClient(url,username,password)
Request request = new Request(downloadURL); //I'm downloading file content of an URL.
Response response = client.executeGet(request);
String response1 = response.getResponseBody();
InputStream is = new ByteArrayInputStream(response.getBytes());
response.setContentType("Content-type",application/pdf); //here response is //javax.servlet.HttpServletResponse
response.setHeader("Content-Disposition","attachment;filename="myfile.pdf");
IOUtils.copy(is,response.getOutPutStream());
response.flushBuffer();
With this code I could download the file but when I open the file and verified there is no data.
As part of response body also I can see some data.
Could you please help me out where I'm doing mistake I tried many options but did not find solution.
How can you use setContentType like this
response.setContentType("Content-type",application/pdf);
If only one avalible param in this method is String void setContentType(String type) so your method should be:
response.setContentType("application/pdf");
Java Doc to be sure.

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

Categories

Resources