public static String sendPostFile(String url, Map<String, Object> params, File file) {
String resString = "";
//1:创建一个httpclient对象
HttpClient httpclient = new DefaultHttpClient();
Charset charset = Charset.forName("UTF-8");//设置编码
try {
//2:创建http的发送方式对象,是GET还是post
HttpPost httppost = new HttpPost(url);
//3:创建要发送的实体,就是key-value的这种结构,借助于这个类,可以实现文件和参数同时上传,很简单的。
@SuppressWarnings("deprecation")
MultipartEntity reqEntity = new MultipartEntity();
//FileBody bin = new FileBody(new File("C:/Users/kin.liufu.2GOTECH/Desktop/资料/Go.XML Message Protocol Specification (V2.88h).doc"));
FileBody bin = new FileBody(new File(file.getPath()));
StringBody comment = new StringBody("房子类型为三房一厅",charset);
ArrayList<FileBody> fileBodys = new ArrayList<>();
fileBodys.add(bin);
for (Map.Entry<String, Object> entry : params.entrySet()) {
System.out.println(entry.getKey()+"--"+entry.getValue().toString());
reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), charset));
}
reqEntity.addPart("file",bin);
httppost.setEntity(reqEntity);
//4:执行httppost对象,从而获得信息
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
//获得返回来的信息,转化为字符串string
resString = EntityUtils.toString(resEntity);
System.out.println("上传是否:"+resString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
return resString;
}