Upload file using HTTP address in Java

I am writing a Java desktop application to upload a file to a folder on an 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 in the destination folder (Test). Content is not written to the file.

What is wrong with this program?

+3
source share
2 answers

After completing the loop in which you write BufferedOutputStream, call bos.close(). This clears the buffered data before closing the stream.

+5
source

Possible error: bis.read () may return a valid 0. You will need to change the condition while while na> = 0.

+1
source

Source: https://habr.com/ru/post/1757632/


All Articles