HTTP Post form 经验记录

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值