首先,我相信您应该在写入图像后调用io.flush(),然后再调用io.close().
第二内容类型对我来说似乎很奇怪.您似乎在尝试提交实际上是图像的表单.我不知道您的ASP期望什么,但是通常,当我编写应通过HTTP传输文件的代码时,我会发送适当的内容类型,例如图片/ jpeg.
例如,这是我从一个小实用程序中提取的代码片段,该小实用程序是我编写的并且在当前工作中正在使用:
URL url = new URL("http://localhost:8080/handler");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "image/jpeg");
con.setRequestMethod("POST");
InputStream in = new FileInputStream("c:/temp/poc/img/mytest2.jpg");
OutputStream out = con.getOutputStream();
copy(in, con.getOutputStream());
out.flush();
out.close();
BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));
// obviously it is not required to print the response. But you have
// to call con.getInputStream(). The connection is really established only
// when getInputStream() is called.
System.out.println("Output:");
for (String line = r.readLine(); line != null; line = r.readLine()) {
System.out.println(line);
}
我在这里使用了从Jakarta IO utils获取的copy()方法.这是供参考的代码:
protected static long copy(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[12288]; // 12K
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
显然,服务器端必须准备好直接从POST主体读取图像内容.
我希望这有帮助.