0

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 ?

DT7
  • 1,615
  • 14
  • 26
Parameswar
  • 1,951
  • 9
  • 34
  • 57

1 Answers1

2

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

Community
  • 1
  • 1
dardo
  • 4,870
  • 4
  • 35
  • 52
  • So , the file cant be downloaded directly ?may be i am dump, but if i set the content type properly, will the file be downloaded automatically ? – Parameswar Oct 09 '13 at 16:32
  • Well what do you mean download automatically, it's sending you a stream back, you need to take that stream and do something with it, whether it be writing it to file, creating a java object, whatever. – dardo Oct 09 '13 at 16:34
  • Ok, for a simple file, that might suffice,My concern is sometimes the file returned from the server may be a jar file, so what could we do ? – Parameswar Oct 09 '13 at 16:38
  • Read the incoming bytes – dardo Oct 09 '13 at 16:41
  • Just clarifying something, when we access some urls in the browser, there is an option to download the files by a pop, i was expecting the same using java .i.e, when i run the program, can the file be saved in a path mentioned in the program ? – Parameswar Oct 09 '13 at 17:15
  • Java is a programming language, you would have to implement the pop up that occurs asking the user where to save the file. – dardo Oct 09 '13 at 18:48
  • Thanks for responding, can i have a link for download in ajax ? when i try this request in ajax and html, i can print the response contents which is the content of the file, but i am stuck up with the download link part – Parameswar Oct 09 '13 at 18:55
  • Look at the link he posted in his answer. It tells you exactly what to do. – aglassman Oct 09 '13 at 19:03