java通过multipart/form-data POST提交参数与文件

in 编程 with 0 comment

# 因公司要把车辆进出图片file以及相关参数上传至另一台服务器,代码如下:

HttpClient context = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1:33333///*****");
post.setHeader("Accept-Language","zh-CN,zh;q=0.9");
post.setHeader("Accept-Encoding","gzip, deflate");//像header这些自己去设置吧
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.RFC6532);//解决中文文件名乱码问题
builder.setCharset(Charset.forName("utf-8"));//指定编码格式
ContentType contentType = ContentType.create("multipart/form-data", HTTP.UTF_8);
ContentType contentTypeImage = ContentType.create("image/png");
builder.addTextBody("communityName", "春田花花",contentType); //添加文本类型参数
builder.addTextBody("cameraBrand", "华夏",contentType); //添加文本类型参数
builder.addTextBody("cameraType", "100-2",contentType); //添加文本类型参数
builder.addTextBody("cameraNumber", "123456",contentType); //添加文本类型参数
builder.addTextBody("licensePlate", "苏A12345",contentType); //添加文本类型参数
builder.addTextBody("colorPlate", "蓝色",contentType); //添加文本类型参数
builder.addTextBody("snapTime", "2020-01-10",contentType); //添加文本类型参数
builder.addBinaryBody("snapPhotoMul",new File("D:/111.png"),contentTypeImage,file.fileName);//添加文件
builder.addTextBody("crossChannel", "10001",contentType); //添加文本类型参数
post.setEntity(builder.build());
HttpResponse response = null;
try
catch (IOException e) {
e.printStackTrace();
}
String result =null;
//获取参数
/请求发送成功,并得到响应/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity res = response.getEntity();
if (res != null) {
try {
result = EntityUtils.toString(res, CHARSET_UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(result);