我正在尝试通过 URLConnection 和 multipart/form-data 上传文件并发布一些变量。但是服务器上的请求是空的。
我已经编写了一个非常基本的 PHP 脚本来制作解决方案的原型。目前代码如下所示:
$uploaddir = './uploads/';
$uploadfile = $uploaddir . basename($_FILES['file1']['name']);
if(move_uploaded_file($_FILES['file1']['tmp_name'], $uploadfile)) {
echo 'success ' . $_POST['input1'] . ' ' . $_POST['input2'];
} else {
echo 'error ';
var_dump($_FILES);
echo ' ';
var_dump($_POST);
}
我的 Java 测试代码如下所示:
URL url = new URL(DEST_URL);
String boundary = "---------------------" + Long.toString(System.currentTimeMillis());
PrintWriter writer = null;
URLConnection con = url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = con.getOutputStream();
InputStream input = new FileInputStream(new File(FILE_PATH));
writer = new PrintWriter(new OutputStreamWriter(output));
writer.println(boundary);
writer.println("Content-Disposition: form-data; name=\"input1\"");
writer.println();
writer.println("1234");
writer.flush();
writer.println(boundary);
writer.println("Content-Disposition: form-data; name=\"input1\"");
writer.println();
writer.println("asdf");
writer.flush();
writer.println(boundary);
writer.println("Content-Disposition: form-data; name=\"file1\"; filename=\"clicknpoint.png\"");
writer.println("Content-Type: image/png");
writer.flush();
int length = 0;
byte[] buffer = new byte[1024];
for(length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
input.close();
writer.println();
writer.println(boundary);
writer.flush();
input = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String cur = null;
StringBuffer buf = new StringBuffer();
while((cur = reader.readLine()) != null) {
buf.append(cur);
}
System.out.println(buf.toString());
Assert.assertTrue(buf.toString().startsWith("success"));
测试用例失败并打印
error array(0) {} array(0) {}
我已经用wireshark检查了请求。这就是发送的内容:
POST /test/upload.php HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------1350394409130
User-Agent: Java/1.6.0_33
Host: localhost
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 94528
---------------------1350394409130
Content-Disposition: form-data; name="input1"
1234
---------------------1350394409130
Content-Disposition: form-data; name="input1"
asdf
---------------------1350394409130
Content-Disposition: form-data; name="file1"; filename="clicknpoint.png"
Content-Type: image/png
.PNG
.
...
IHDR..............d<.....sRGB.........gAMA......a.....pHYs..........o.d....IDATx^..}.FWy......c,UU.....|.($. .B1..4%..(MC. ...(..j..."<.I.dD.&.DD.&q..Y....P..\..v.!..k...1v....m. // and so on
知道有什么问题吗?