使用Java中的HTTP上传文件

dhi*_*vya 3 java

我正在用Java编写桌面应用程序,使用HTTP PUT将文件上传到IIS服务器上的文件夹.

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();
  }
Run Code Online (Sandbox Code Playgroud)

此程序在目标文件夹(Test)上创建一个空文件.内容不会写入文件.

这个程序有什么问题?

Dev*_*ler 5

在完成编写的循环后BufferedOutputStream,调用bos.close().在关闭流之前刷新缓冲的数据.