使用Java中的HTTP上传文件

时间:2010-08-02 10:22:13

标签: 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();
  }

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

这个程序有什么问题?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

可能的错误:bis.read()可以返回有效的0.您需要将while条件更改为&gt; = 0.