Java make POST request to express js server and download PDF file - java

I have express js server as API. I need to send POST request to that server and my website needs to download PDF file to the client computer.
Here is my express server code:
const pdf = await generatePDF(data.originURL, data.url, data.pageOrientation); //pdf generation
// send pdf to client
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=file.pdf',
'Content-Length': pdf.length
});
res.end(pdf);
In my website I have commandButton which call the action for POST request;
What I'm a doing wrong, I'm not getting any downloaded file in my website?
Method for making POST request:
public void makeRequest() {
HttpURLConnection connection = null;
try {
String imageExportServer = "url....";
URL url = new URL(imageExportServer);
connection = (HttpURLConnection)url.openConnection();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStream stream = connection.getOutputStream()) {
JsonObject configJson = new JsonObject();
configJson.addProperty("originURL", "url");
configJson.addProperty("url", "url...");
configJson.addProperty("pageOrientation", "someText");
stream.write(Builder().create().toJson(configJson).getBytes());
}
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
//log.warn("Error response: ", responseCode);
}
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = connection.getInputStream();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream("neki.pdf");
int bytesRead = -1;
byte[] buffer = new byte[contentLength];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
FileOutputStream fos = new FileOutputStream("neki.pdf");
fos.write(buffer);
fos.close();
System.out.println("File downloaded");
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
//log.info("Exporting chart of type '%s' took %sms.", "tyoe", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception e) {
//log.warn(e.getMessage(), e);
}
}
}
}

Related

HttpURLConnection not able to read 302 Response code

I am trying to download a file through code and it is working if the file is found. But if the Link returns a 302 code, I am getting a connection timeout through code. It is working fine in browser.
Can someone help me out where I am going wrong?
My code is given below:
private static void downloadFile(String fileUrl, String fileName) {
HttpURLConnection connection = null;
try {
URL url = new URL(fileUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.connect();
int code = connection.getResponseCode();
String message = connection.getResponseMessage();
System.out.println(code + "-" + message);
if (code == HttpURLConnection.HTTP_OK) {
try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
throw new Exception("Invalid Response Code: " + code + ", Response Message: " + message);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Working URL(200): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo16SEP2022bhav.csv.zip
Timeout URL(302): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo17SEP2022bhav.csv.zip
A setting
connection.setInstanceFollowRedirects(true); // follow response codes 3xx
connection = (HttpURLConnection) new URL(fileUrl).openConnection();
connection.setInstanceFollowRedirects(true); // follow response codes 3xx
connection.setRequestMethod("GET");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.connect();

HttpUrlConnection Reading an Input Stream Returns "-1"

I am sending a post request to a server. After a successful request, the response sends pdf data to the client for download. I am trying to generate the pdf file with the response and save it to the Android device. I have successfully created the request, the empty pdf file, and I have even received a successful response. Although, when I call .getInputStream() it returns a "-1". As a result, the while loop exits with the error java.lang.ArrayIndexOutOfBoundsException: length=4096; regionStart=0; regionLength=-1.
I understand why I am receiving this error, but I do not know how to get the data response.
protected Boolean doInBackground(String... params) {
Log.d("LOGOUT", "CREATING REQUEST");
boolean successful = false;
HttpURLConnection connection = null;
URL downloadURL = null;
InputStream inputStream = null;
PrintWriter out= null;
FileOutputStream fileOutputStream = null;
File file = null;
int totalsize;
try {
downloadURL = new URL("http://exampleurl.com");
connection = (HttpURLConnection) downloadURL.openConnection();
connection.setDoOutput(true);
String data = "param=" + URLEncoder.encode(params[0], "UTF-8") + "&submit=" + URLEncoder.encode("Submit", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + data.length());
String sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
file = new File(sdCard + File.separator + "test.pdf");
fileOutputStream = new FileOutputStream(file);
out = new PrintWriter(connection.getOutputStream());
out.write(data);
out.close();
inputStream = connection.getInputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) ; {
Log.d("LOGOUT", "BUFFER: " + read);
// **The LOGOUT message reads "BUFFER: -1" within Logcat**
fileOutputStream.write(buffer, 0, read);
}
successful = true;
} catch (MalformedURLException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (UnsupportedEncodingException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (FileNotFoundException e) {
Log.d("LOGOUT", "ERROR: " + e);
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
} finally {
if (inputStream != null) {
try {
Log.d("LOGOUT", "CLOSING INPUTSTREAM");
inputStream.close();
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
Log.d("LOGOUT", "CLOSING FILEOUTPUTSTREAM");
} catch (IOException e) {
Log.d("LOGOUT", "ERROR: " + e);
}
}
}
if (connection != null) {
Log.d("LOGOUT", "CLOSING CONNECTION");
connection.disconnect();
}
}
return successful;
}
I am receiving the correct response headers. I have listed them below...
Connection:Keep-Alive
Content-Disposition:attachment; filename=examplefilename.pdf
Content-Type:application/pdf
Date:Wed, 21 Oct 2015 13:59:45 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.22
Transfer-Encoding:chunked
Vary:User-Agent
X-Powered-By:PHP/5.3.29
I know for a fact I am sending/receiving a successful request/response, but I am unable to download the pdf data. Finally, I do not have control over the server. I am interacting with a third party application.
What am I doing wrong to accomplish the task? If not that, does anyone have any idea on where I could look to solve the problem? Any guidance is appreciated.

Android : Sending image as byte[] by Http Get or Post Request

I need to upload image to the web server and it require the ImageContent to be in byte[] at the documentation it said base64Binary but i tried base64 encoded string and no use
that is my class :
private class background extends AsyncTask<byte[],Void,String> {
String url = "http://www.sample.com/_mobfiles/CLS_Account.asmx/UploadImage";
String charset = "UTF-8";
String param1 = "jpg";
#Override
protected String doInBackground(byte[]... params) {
try {
String query = String.format("ImageContent=%s&imageExtenstion=%s", params[0], URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
else {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = response.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] arr = buffer.toByteArray();
String decoded = new String(arr, "UTF-8");
System.out.println(decoded);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
that return (java.io.FileNotFoundException)
and the Base64 Encoded return (java.net.ProtocolException: Unexpected status line: Object moved)
Here is the Doc :
HTTP GET
The following is a sample HTTP GET request and response. The placeholders shown need to be replaced with actual values.
GET /_mobfiles/CLS_Account.asmx/UploadImage?ImageContent=base64Binary&imageExtenstion=string HTTP/1.1
Host: www.sample.com
and the response is like
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
HTTP POST
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
POST /_mobfiles/CLS_Account.asmx/UploadImage HTTP/1.1
Host: www.sample.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
ImageContent=base64Binary&imageExtenstion=string
and the response is like
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
Can you try this in your chrome console and tell the output.
xmlhttp=new XMLHttpRequest();
var url = '/_mobfiles/CLS_Account.asmx/UploadImage?';
var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='
xmlhttp.open("GET",url + 'ImageContent='+base64+'&imageExtenstion=gif',true);
xmlhttp.send();
console.log(xmlhttp.response)
Try this too. If this also fails you gotta check the server. Atleast provide server method responsible for handling this.
xmlhttp=new XMLHttpRequest();
var url = '/_mobfiles/CLS_Account.asmx/UploadImage?';
var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='
xmlhttp.open("POST",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('ImageContent="'+base64+'"&imageExtenstion="gif"');
console.log(xmlhttp)
Use a Get request and use
var base64 ='R0lGODlhDwAPAKECAAAAzMzM%2F%2F%2F%2F%2FwAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH%2BH09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw%3D%3D'
I am sure this should work. I am really sorry My bad I should haven't made such a stupid mistake/
I haven't found a way but to send the whole SOAP envelope
So from a background thread AsyncTask i called callSOAPWebService(String data) when executed
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap resizedBitmap = Bitmap.createScaledBitmap(thumbnail, 150, 150, false);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100,stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
new ImageUpload().execute(encoded);
from the UI thread
and on background
#Override
protected String doInBackground(String... params) {
callSOAPWebService(params[0]);
return null;
}
and the callSOAPWebService is as follow
private boolean callSOAPWebService(String data) {
OutputStream out = null;
int respCode;
boolean isSuccess = false;
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(GetData.NonOpDomain);
httpURLConnection = (HttpURLConnection) url.openConnection();
do {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("Content-Type", "text/xml");
httpURLConnection.setRequestProperty("SendChunked", "True");
httpURLConnection.setRequestProperty("UseCookieContainer", "True");
HttpURLConnection.setFollowRedirects(false);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(true);
httpURLConnection.setRequestProperty("Content-length", getReqData(data).length + "");
httpURLConnection.setReadTimeout(100 * 1000);
// httpURLConnection.setConnectTimeout(10 * 1000);
httpURLConnection.connect();
out = httpURLConnection.getOutputStream();
if (out != null) {
out.write(getReqData(data));
out.flush();
}
respCode = httpURLConnection.getResponseCode();
Log.e("respCode", ":" + respCode);
} while (respCode == -1);
// If it works fine
if (respCode == 200) {
try {
InputStream responce = httpURLConnection.getInputStream();
String str = convertStreamToString(responce);
System.out.println(".....data....." + str);
InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(is, null);
parseXMLAndStoreIt(myparser);
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
isSuccess = false;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out = null;
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
return isSuccess;
}
and the helper method
public volatile boolean parsingComplete = true;
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("UploadImageResult")) {
uploadedImage = text;
uploadedImage = uploadedImage.replace("\"", "");
}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public static String createSoapHeader() {
String soapHeader;
soapHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + ">";
return soapHeader;
}
public static byte[] getReqData(String data) {
StringBuilder requestData = new StringBuilder();
requestData.append(createSoapHeader());
requestData.append("<soap:Body>" + "<UploadImage" + " xmlns=\"http://example.org/\">" + "<ImageContent>").append(data).append("</ImageContent>\n").append("<imageExtenstion>jpg</imageExtenstion>").append("</UploadImage> </soap:Body> </soap:Envelope>");
Log.d("reqData: ", requestData.toString());
return requestData.toString().trim().getBytes();
}
private static String convertStreamToString(InputStream is)
throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Hope it will help some one in the future

How to get a file name from response header from HttpURLConnection?

I have Client Server program, Client make a connection to server with its URL and server Reads a file and writes to outputstream and client will get that file and save it in a directory. Problem is I am not getting the filename I am sending in response from Server. Here is my Client Server Code.
Client,
private void receiveFile() throws IOException {
String url11="http://localhost:8080/TestServer/TestServer";
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
int responseCode = httpConn.getResponseCode();
String ff=httpConn.getHeaderField("filename");
System.out.println("FHeader :"+ff);
File saveFile = new File(SAVE_DIR + ff);
StringBuilder builder = new StringBuilder();
builder.append(httpConn.getResponseCode())
.append(" ")
.append(httpConn.getResponseMessage())
.append("\n");
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
System.out.println(builder);
InputStream inputStream = httpConn.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
Server ,
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
String filePath = "E:\\Docs\\Next stop is Kurki.MP3";
File fileMp3 = new File(filePath);
if(fileMp3.exists()){
System.out.println("FOUND : ");
} else {
System.out.println("FNF");
}
String fNmae=fileMp3.getName();
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fNmae + "\"");
response.addHeader("fName", fNmae);
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();
try {
int byteRead = 0;
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
// downloadComplete = "-1";
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
}
I feel everything is correct in Server side , Can any one help me to sort this. It would be great help . thank you.
Try this in server:
File file = new File("E:\\Docs\\Next stop is Kurki.MP3");
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename="Next stop is Kurki.MP3");
return response.build();
When client is android :
wv = webView;
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/YouPath", fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Attention here in client String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)

Programmatically downloading files pushed through a PHP page

Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}

Categories