public static void post() throws ClientProtocolException, IOException {
// Proxy p=new Proxy();
// p.setHost("192.168.1.153");
// p.setPort("8888");
HttpClient httpclient = new DefaultHttpClient();
// HttpHost proxy = new HttpHost(p.getHost(), Integer.valueOf(p.getPort()), "http");
// httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
//请求路径
HttpPost post = new HttpPost("xxxxx");
//添加header头信息
post.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)");
//注 这里一定不能添加 content-Type:multipart/form-data 属性 因为这里面有个boundary参数属性是不可控的。这个值是由浏览器生成的。如果强行指明和可能
//导致边界值不一致 就会请求失败 详细参见 http://blog.csdn.net/xiaojianpitt/article/details/6856536
// post.setHeader("content-Type", "multipart/form-data");
post.setHeader("Host", "****");
post.setHeader("Accept-Encoding","gzip");
post.setHeader("charset", "utf-8");
FileBody fileBody = new FileBody(new File("xxxx"),"image/pjpeg","utf-8");
MultipartEntity entity = new MultipartEntity();
//添加消息体信息
entity.addPart("xxxx", new StringBody("xxx",Charset.forName("utf-8")));
entity.addPart("imagefile", fileBody);
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
HttpEntity entitys = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entitys));
}
}
httpclient.getConnectionManager().shutdown();
}
如果设置了content-Type: multipart/form-data
可以使用抓包工具拦截请求
这是是缺少boundary参数的
正常的应该是存在的(边界值不一样就会导致content-length=0 就是发送的消息体是空的)