Read file of content-disposition with java - 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

Related

Upload file using java MultipartEntityBuilder throws Content too long. What's an alternative?

I'm trying to make a little utility that will synchronise data between two servers. Most of the calls there are REST calls with JSON, so I decided to use Apache HttpClient for this.
There is however a section where I need to upload a file. I'm trying to do this using the mutipart form data with the MutipartEntityBuilder but I encounter a Content too long problem. (I tried to gzip the contents of the file too, but I'm still going over the limit).
Here's my java code:
HttpPost request = new HttpPost(baseUrl+URL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//create upload file params
builder.addTextBody("scanName", "Test upload");
builder.addBinaryBody("myfile", f);
HttpEntity params= builder.build();
request.setEntity(params);
request.addHeader("content-type","multipart/form-data");
HttpResponse response = httpClient.execute(request);
Are there better atlernatives that I should be using for the file upload part? I'm also going to download the files from one of the server. Will I hit a similar issue when try to handle those responses?
Is there something I'm doing wrong?
I try to use your code and send some file with size something about 33MB and it was successful. So, I think your problem one of the follows:
Created http client has limitations for request size - in this case you need to change properties of client or use another client;
In some peace of code you call HttpEntity.getContent() method. For multipart request for this method exists limitations - 25kB. For this case you need to use writeTo(OutputStream) instead of getContent()
In comments you told about swagger, but I don't understand what does it mean. If you use swagger generated api, that problems maybe occurred at their code and you need to fix generation logic (or something like this - I never used swagger)
I hope my answer will help you

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

Send xml as part of URL request in Java

This might be a trivial question but I'm trying to send web request to USPS to get a http post response (or email response depending on my request) containing the tracking information based on the tracking number that I send in. The documentation says the xml needs to appended as part of the url like below
http://secure.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<PTSEmailRequest USERID="xxxxx"><TrackId>xxxxx</TrackId><RequestType>EN</RequestType></PTSEmailRequest>
I saw there were 2 ways to make an xml request, one using HttpPost and the other URLConnection. I'm a bit thrown by how I go about this and I'm failing to appreciate what's the difference between appending xml in the url and a normal http request. Can someone please clear things up for me?
USPS documentation for tracking =>
https://www.usps.com/business/web-tools-apis/track-and-confirm.pdf
I read these related Stackoverflow posts
Java: How to send a XML request?
posting XML request in java
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://secure.shippingapis.com/ShippingAPITest.dll");
List<String> params = new ArrayList<String>(2);
params.add(new BasicNameValuePair("API", "TrackV2"));
params.add(new BasicNameValuePair("XML", FuncTOGenerateXML()));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
//.....
// .....
instream.close();
}
An HTTP request can use one of several methods, like POST, GET, DELETE, PUT... Here we talk about POST and GET
Technical differences
With GET, the data is retrieved from the parameters in the URL.
With POST, the data is retrieved from the data transmitted inside the HTTP message.
Intended use differences
GET is intended to be used when the request does not cause a change (v.g., searching in Google). Since you can repeat the request without side effects, the data is in the URL and can be stored in the browser history, favorites, etc.
POST is intended to use when you are performing a change (v.g. sending an e-mail, doing a on-line purchase). The data related is not stored with the URL (it is then that, if you go back to a page that was obtained using POST, the browser many times will show you a pop-up asking for permission to send the data again.
In real usage, the distinction is not so clear cut, in particular POST is sometimes used when the data is too large (URLs have limited length). Also, sometimes GET is used with the meaning of POST so the data can be presented as an HTML link.
Finally, URLConnection is the basic API for opening a connection (which you can use as a POST or GET request, based in how you pass the data, or something else) and HttpPost is just a higher level API for creating a POST request. If you go the basic way, use HttpURLConnection better.

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