3

I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.

URLConnection urlconnection=null;
  try{
   File file = new File("C:/test.txt");
   URL url = new URL("http://192.168.5.27/Test/test.txt");
   urlconnection = url.openConnection();
   urlconnection.setDoOutput(true);
   urlconnection.setDoInput(true);

   if (urlconnection instanceof HttpURLConnection) {
    try {
     ((HttpURLConnection)urlconnection).setRequestMethod("PUT");
     ((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
     ((HttpURLConnection)urlconnection).connect();


    } catch (ProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }


   BufferedOutputStream bos = new BufferedOutputStream(urlconnection
     .getOutputStream());
   BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
     file));
    int i;
    // read byte by byte until end of stream
    while ((i = bis.read()) >0) {
     bos.write(i);
    }
   System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  try {

   InputStream inputStream;
   int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
   if ((responseCode>= 200) &&(responseCode<=202) ) {
    inputStream = ((HttpURLConnection)urlconnection).getInputStream();
    int j;
    while ((j = inputStream.read()) >0) {
     System.out.println(j);
    }

   } else {
    inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
   }
   ((HttpURLConnection)urlconnection).disconnect();

  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

This program creates an empty file on the destination folder (Test). The contents are not written to the file.

What is wrong with this program?

2
  • 1
    I'd start by debugging the server-side - are the bytes actually received? Commented Aug 2, 2010 at 10:24
  • My first approach on write operations that don't produce any content is flushing every stream I have :D Try bos.flush() after writing. Commented Aug 2, 2010 at 10:31

2 Answers 2

5

After you complete the loop where you are writing the BufferedOutputStream, call bos.close(). That flushes the buffered data before closing the stream.

Sign up to request clarification or add additional context in comments.

Comments

1

Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.