使用 Java 中的 HTTP 上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3386832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload a file using HTTP put in Java
提问by dhivya
I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.
我正在用 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();
}
This program creates an empty file on the destination folder (Test). The contents are not written to the file.
该程序在目标文件夹 (Test) 上创建一个空文件。内容不会写入文件。
What is wrong with this program?
这个程序有什么问题?
回答by Devon_C_Miller
After you complete the loop where you are writing the BufferedOutputStream, call bos.close(). That flushes the buffered data before closing the stream.
完成编写 的循环后BufferedOutputStream,调用bos.close(). 在关闭流之前刷新缓冲的数据。
回答by Chen Harel
Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.
可能的错误:bis.read() 可以返回有效的 0。您需要将 while 条件更改为 >= 0。

