我想上传使用Java URL
类的文件,并且我发现堆栈溢出中的previous question这很好地解释了细节,所以我试着按照它进行操作。以下是我的代码,采用answer中给出的sniplet。使用Java URL类将数据写入服务器是否需要服务器响应?
我的问题是,如果我不作出的connection.getResponseCode()
一个或connection.getInputStream()
或connection.getResponseMessage()
或任何其从服务器到REPONSE相关的呼叫,请求将永远不会被发送到服务器。为什么我需要这样做?或者有什么方法可以在没有得到响应的情况下写入数据?
P.S.我开发了一个服务器端上传servlet,它接受multipart/form-data
并使用FileUpload
将它保存到文件中。它是稳定的,毫无问题地工作,所以这不是我的问题产生的地方。
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class URLUploader {
public static void closeQuietly(Closeable... objs) {
for (Closeable closeable : objs) {
IOUtils.closeQuietly(closeable);
}
}
public static void main(String[] args) throws IOException {
File textFile = new File("D:\\file.zip");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/upslet/upload").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
// Send text file.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"file1\"; filename=\"" + textFile.getName() + "\"");
writer.println("Content-Type: application/octet-stream");
FileInputStream fin = new FileInputStream(textFile);
writer.println();
IOUtils.copy(fin, output);
writer.println();
// End of multipart/form-data.
writer.println("--" + boundary + "--");
output.flush();
closeQuietly(fin, writer, output);
// Above request will never be sent if .getInputStream() or .getResponseCode() or .getResponseMessage() does not get called.
connection.getResponseCode();
}
}
谢谢你挑选那个。我已纠正它。但是,编译失败并没有错。它只是重复。 – gigadot 2012-02-08 22:11:04