Error writing to server - java

I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}

It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?

Related

Why the outputStream isn't working without inputStream?

I have tried to connect a PHP script on localHost, but the script isn't accessed without the presence of inputStream. Accidentally I made the code working, but don't know why it is working in presence of inputStream but not in absence of inputStream
try {
String url= "10.0.2.2/arrival.php";
URL loginurl= new URL(url);
HttpURLConnection http= (HttpURLConnection)loginurl.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDoInput(true);
OutputStream out= http.getOutputStream();
BufferedWriter bfwr= new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
String post_data= URLEncoder.encode("renter_id","UTF-8")+"="+URLEncoder.encode(renter_id,"UTF-8");
bfwr.write(post_data);
bfwr.flush();
out.close();
bfwr.close();
InputStream inpt= http.getInputStream();
BufferedReader bfrdr= new BufferedReader(new InputStreamReader(inpt,"iso-8859-1"));
String line="";
String result="";
while((line=bfrdr.readLine())!=null){
result+=line;
}
bfrdr.close();
inpt.close();
http.disconnect();
return "";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

After downloading whole (84M) file from dropbox it turning into 0 bytes

I am downloading a zip file from dropbox. When it keeps downloading I measure the file size and get it is increasing its size with the Below code. It downloads whole 84M and after finishing download it turns into 0 bytes. What wrong am I actually doing?
public static void downloadDropBox(File file) {
String url = "https://www.dropbox.com/sh/jx4b2wvqg8d4ze1/AAA0J3LztkRc6FJ5tKy4dUKha?dl=1";
int bytesRead;
byte[] bytesArray = new byte[1024];
InputStream is = null;
FileOutputStream outputStream = null;
long progres = 0;
try {
URL fileUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
connection.connect();
is = connection.getInputStream();
outputStream = new FileOutputStream(file);
while ((bytesRead = is.read(bytesArray, 0, 1024)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
During download file:
After Finishing download file:

Error handling for URLConnection

I have this method that downloads .csv files from yahoo finance and saves them locally. It is accessed during a loop so it is downloading many files from a list. However sometimes a symbol is entered incorrectly, no longer exists, or the connection times out. How can I amend this method so that connection time outs are retried and incorrect symbols (meaning the url does not work) are just skipped over without ending the program?
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Why not call the method again when an exception is thrown. You can narrow down the exception type to indicate when a retry should be initiated.
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}

File download from url on MAC OSX?

AM trying to download a file from the net using the url & urlconnection class in java using this code.
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(destination);
} catch (FileNotFoundException ex) {
}
try {
URL url = null;
try {
url = new URL("here is the url");
//
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
URLConnection urlc = null;
try {
urlc = url.openConnection();
System.out.println("Conneceted");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
bis = new BufferedInputStream(urlc.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
bos = new BufferedOutputStream(fos);
// System.out.println("absolute path="+destination.getAbsolutePath());
int i;
try {
while ((i = bis.read()) != -1) {
System.out.print((char) i);
bos.write(i);
}
JOptionPane.showMessageDialog(this, "downloadeded sucessfully");
this.dispose();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "could not be diownloaded \n please try again");
ex.printStackTrace();
}
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
When i run this code on my windows system it runs perfectly but when i take my code to mac os it gives me the exception
Exception in thread "Thread-2" java.lang.NullPointerException
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at java.io.FilterOutputStream.close(FilterOutputStream.java:140)
at FileDownloader.Download(FileDownloader.java:201)
at FileDownloader$2.run(FileDownloader.java:114)
at java.lang.Thread.run(Thread.java:637)
Could anyone tell me what the reason may be? and how i can solve this?
Thanks in advance

how to resume an interrupted download

I'm trying to download a large file from my Yahoo! web site server which apparently is setup (not by me) to disconnect downloads if they are not completed within 100 seconds. The file is small enough to usually successfully transfer. On the occasions when the data rate is slow and the download gets disconnected, is there a way to resume the URLConnection at the file offset where the disconnection occurred? Here's the code:
// Setup connection.
URL url = new URL(strUrl[0]);
URLConnection cx = url.openConnection();
cx.connect();
// Setup streams and buffers.
int lengthFile = cx.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(strUrl[1]);
byte data[] = new byte[1024];
// Download file.
for (total=0; (count=input.read(data, 0, 1024)) != -1; total+=count) {
publishProgress((int)(total*100/lengthFile));
output.write(data, 0, count);
Log.d("AsyncDownloadFile", "bytes: " + total);
}
// Close streams.
output.flush();
output.close();
input.close();
Try using a "Range" request header:
// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// here "downloaded" is the data length already previously downloaded.
// Connect to server.
connection.connect();
Having done that, you can seek at a given point (just before the length of your download data, say X) and start writing the newly downloaded data there. Be sure to use the same value X for the range header.
Details about 14.35.2 Range Retrieval Requests
More details and source code can be found here
Here's an example code that you can use:
import java.io.*;
import java.net.*;
public class HttpUrlDownload {
public static void main(String[] args) {
String strUrl = "http://VRSDLSCEN001:80//DLS//lib//clics.jar";
String DESTINATION_PATH = "clics.jar";
int count = 0;
while (true) {
count++;
if (download(strUrl, DESTINATION_PATH) == true || count > 20) {
break;
}
}
}
public static boolean download(String strUrl, String DESTINATION_PATH) {
BufferedInputStream in = null;
FileOutputStream fos = null;
BufferedOutputStream bout = null;
URLConnection connection = null;
int downloaded = 0;
try {
System.out.println("mark ... download start");
URL url = new URL(strUrl);
connection = url.openConnection();
File file=new File(DESTINATION_PATH);
if(file.exists()){
downloaded = (int) file.length();
}
if (downloaded == 0) {
connection.connect();
}
else {
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
connection.connect();
}
try {
in = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
int responseCode = 0;
try {
responseCode = ((HttpURLConnection)connection).getResponseCode();
} catch (IOException e1) {
e1.printStackTrace();
}
if (responseCode == 416) {
return true;
} else {
e.printStackTrace();
return false;
}
}
fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
}
in.close();
bout.flush();
bout.close();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
if (bout != null) {
try {
bout.close();
} catch (IOException e) {
}
}
if (connection != null) {
((HttpURLConnection)connection).disconnect();
}
}
}
}

Categories

Resources