我正在尝试上传文件并通过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
知道什么是错的吗?
答案 0 :(得分:0)
问题是无效边界。边界必须以额外的“ - ”开头,并且请求必须以“ - ”+ border +“ - ”结束。“/ p>
这里缺少。