首先我相信你应该打电话io.flush()
进而io.close()
写入图像后。
第二种内容类型对我来说似乎很奇怪。看来您正在尝试提交表单,而它实际上是图像。我不知道你的 asp 期望什么,但通常当我编写应该通过 HTTP 传输文件的代码时,我会发送适当的内容类型,例如image/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 正文读取图像内容。
我希望这有帮助。