您的位置:首页 > 理论基础 > 计算机网络

httpclient模拟表单上传参数和文件

2018-02-08 11:53 309 查看
上传文件需要添加httpmime.jar支持,mime多用途互联网邮件扩展类型。
/**
* 表单提交参数和文件
* @param params
* @param files
* @return
*/
public static String postForm(String urlPath, Map<String, String> params, List<File> files){

System.out.println("请求地址:"+urlPath);
HttpPost httpPost = new HttpPost(urlPath);

CloseableHttpClient httpClient = HttpClients.createDefault();

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

// 文件参数
if(files!=null&&files.size()>0){
// for(File file : files){
// FileBody fileBody = new FileBody(file);
// // <input type="file" name="fileName"/>
// entityBuilder.addPart(file.getName(), fileBody);

// }
// 用特定的字段名,接收方用对应的字段名接收
entityBuilder.addPart("file3", new FileBody(files.get(0)));
entityBuilder.addPart("file4", new FileBody(files.get(1)));

}
// 字符串参数
if(params!=null&&!params.isEmpty()){
for(String key : params.keySet()){
StringBody stringBody = new StringBody(params.get(key), ContentType.create("text/plain", CHARSET));
// <input type="text" name="userName" value="userName">
entityBuilder.addPart(key, stringBody);
}
}

try {
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);

RequestConfig config = RequestConfig.custom()
.setConnectTimeout(TIMEOUT)
.setSocketTimeout(TIMEOUT) // read time out
.build();
httpPost.setConfig(config); // 请求配置

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
int responseCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("【状态码:"+responseCode+"】");
InputStream in = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String readLine = null;
while((readLine=bufferedReader.readLine())!=null){
sb.append(readLine);
}
System.out.println("返回报文:"+sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
System.out.println("请求异常");
return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: