post form的格式一定不能变,特别是form中关于data部分的格式。昨晚的BUG就是由于在form中data部分多增加了Content-Length,画蛇添足,导致服务器接收到的data数据体中有多出来的字符(多出来的字符就是Content-Length)。Content-Length应该放在Http头中赋值。特此记录。
另外,post form不可压缩,否则服务器无法识别。
最后,附上form的正确格式:
HTTP HEADER:
Content-Type:multipart/form-data; boundary=------UploadBoundary------
HTTP BODY:
--------UploadBoundary------
Content-Disposition: form-data; name="shopid"
50000
--------UploadBoundary------
Content-Disposition: form-data; name="name"
照片名(utf-8)
--------UploadBoundary------
Content-Disposition: form-data; name="token"
309afac7f5734be7fea7c660b54f2f42dfa9ae83ed6f9c6e789dad6d4449d397b6b7c434497b2801ac5e5ba0a25aeb6d242910b4d98b40f497f252efe239603c986fda9083c1eab7b8802dd4ee0c309baaac8b7dbdcc8f24769e661858184267
--------UploadBoundary------
Content-Disposition: form-data; name="photo"; filename="whatever.jpg"
Content-Type: image/jpg
Content-Transfer-Encoding: binary
JPG数据
--------UploadBoundary--------
SAMPLE CODE (JAVA):
String CRLF = "/r/n";
String BOUNDARY = "--------UploadBoundary------";
ByteArrayBuffer buffer = new ByteArrayBuffer(data.length + 1000);
post.setHeader("Content-Type", "multipart/form-data; boundary=------UploadBoundary------");
// shopid
buffer.append(BOUNDARY);
buffer.append(CRLF);
buffer.append("Content-Disposition: form-data; name=/"shopid/"");
buffer.append(CRLF);
buffer.append(shopid);
// name
buffer.append(BOUNDARY);
buffer.append(CRLF);
buffer.append("Content-Disposition: form-data; name=/"name/"");
buffer.append(CRLF);
buffer.append(name.toCharArray("utf-8"));
// token
buffer.append(BOUNDARY);
buffer.append(CRLF);
buffer.append("Content-Disposition: form-data; name=/"token/"");
buffer.append(CRLF);
buffer.append(token);
// data
buffer.append(BOUNDARY);
buffer.append(CRLF);
buffer.append("Content-Disposition: form-data; name=/"photo/"; filename=/"whatever.jpg/"");
buffer.append(CRLF);
buffer.append("Content-Type: image/jpg");
buffer.append(CRLF);
buffer.append("Content-Transfer-Encoding: binary");
buffer.append(CRLF);
buffer.append(CRLF);
buffer.append(data);
buffer.append(CRLF);
buffer.append(BOUNDARY);
buffer.append("--");
buffer.append(CRLF);
ByteArrayEntity entity = new ByteArrayEntity(buffer.toByteArray());
post.setEntity(entity);
return entity;