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

httpclient4.5如何以二进制流的形式上传文件

2018-01-15 17:10 701 查看
本人在做接口测试的过程中,遇到了上传文件的测试。由于之前没有测试过流上传,导致花费了一些时间,还有就是网上关于httpclient4.5的资料和其他版本资料混在一起,也浪费了一些时间。经过测试终于可用了。暂时没有进一步封装,下面分享一些主要的代码。其实 httpclient 对象我在一个基础类中以静态变量的形式一开始就加载好了,为了减少理解的障碍,我后面会把创建httpclient 的方法也附带在后面。

public void uploadPic() throws FileNotFoundException {
HttpPost httppost = new HttpPost(url);
// 创建二进制文件流
InputStream inputStream = new FileInputStream(file);
StringBody index = new StringBody("7", ContentType.create("text/plain", Consts.UTF_8));
// 创建 part contentBody,第一个是值,第二个参数是类型,第三个参数是编码格式
// 创建MultipartEntityBuilder对象
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 添加二进制文件流,第一个参数是接口参数名,第二个参数是文件的二进制流,第三个参数是文件名
builder.addBinaryBody("user_pic", inputStream, ContentType.create("multipart/form-data"), "11.png");
// 添加参数和参数值
builder.addPart("user_pic_index", index);
// 创建 httpentity 实体
HttpEntity httpEntity = builder.build();
// 设置 httpentity 实体
httppost.setEntity(httpEntity);
// 发送请求获取相应
JSONObject response = getHttpResponseEntityByJson(httppost);
output(response);
}其中output 方法在另外一篇文章中写过了,这里就不多写了,只是一个格式化输出 json 对象的方法。
下面是getHttpResponseEntityByJson方法:

/**
* 获取响应实体,暂无header设置
*
* @param request
* 请求对象
* @return 返回json类型的对象
*/
public JSONObject getHttpResponseEntityByJson(HttpRequestBase request) {
output(request.getURI());
JSONObject jsonObject = new JSONObject();
CloseableHttpResponse response = null;// 创建响应对象
long data_size = 0;// 用于存放数据大小
Map<String, String> info = getRequestInfo(request);
String api_name = info.get("api_name");
String type = info.get("type");
String host_name = info.get("host_name");
String method = info.get("method");
String uri = info.get("uri");
String params = info.get("params");
request.addHeader(HTTP.USER_AGENT, "okhttp/3.9.1");// 符合应用防火墙
mark = getMark();
Date start = getDate();// 记录开始时间
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e1) {
output("client请求异常", e1);
} catch (IOException e1) {
output("执行请求时java IO 异常!", e1);
} // 获取响应
Date end = getDate();// 记录结束时间
double elapsed_time = outputTimeDiffer(start, end);// 获取响应耗时
int status = response.getStatusLine().getStatusCode();// 获取响应状态
HttpEntity entity = response.getEntity();// 获取响应实体
data_size = entity.getContentLength();// 获取相应数据大小
if (data_size == -1) {// 如果为-1,则重置data_size
data_size = 0;
}
String content = null;
try {
content = EntityUtils.toString(entity, "utf-8");// 用string接收响应实体
EntityUtils.consume(entity);// 消耗响应实体
} catch (ParseException e1) {
output("解析响应实体异常!", e1);
} catch (IOException e1) {
output("解析响应实体时java IO 异常!", e1);
} // 解析响应
try {
response.close();
} catch (IOException e2) {
output("响应关闭失败!", e2);
}
if (data_size == 0) {// 如果被重置或者没有获取到,则data_size等于解析string大小
try {
data_size = content.length();
} catch (Exception e) {
data_size = 1;
output("获取响应长度异常!", e);
}
}
if (status == 200) {
try {
jsonObject = JSONObject.fromObject(content);
} catch (Exception e) {
output("相应状态码错误,相应内容:" + content, e);
}
} else {
output("响应内容:" + content);
}
// request.releaseConnection();//此处容易造成socket close,在连接池时使用
MySqlTest.getInstance().saveApiTestDate(host_name, api_name, data_size, elapsed_time, status, type, mark,
method, uri, params);
return jsonObject;
}

中间涉及到获取信息getRequestInfo方法如下:
/**
* 封装获取请求的各种信息的方法
*
* @param httpRequestBase
* 传入请求对象
* @return 返回一个map,包含api_name,host_name,type,method,params
*/
public Map<String, String> getRequestInfo(HttpRequestBase request) {
Map<String, String> info = new HashMap<>();// 新建map保存信息
String method = request.getMethod();// 获取method
info.put("method", method);
String uri = request.getURI().toString();// 获取uri
info.put("uri", uri);
String url = uri;
if (uri.contains("?")) {// 获取url,如果是get请求,先截取
url = uri.substring(0, uri.indexOf("?"));
}
String one = url.substring(url.indexOf("//") + 2);// 删除掉http://
String api_name = one.substring(one.indexOf("/"));// 获取接口名
info.put("api_name", api_name);
String host_name = one.substring(0, one.indexOf("/"));// 获取host地址
info.put("host_name", host_name);
String type = url.substring(0, url.indexOf("//") - 1);// 获取协议类型
info.put("type", type);
String params = null;// 参数
if (method.equals("GET")) {
params = uri.substring(uri.indexOf("?") + 1, uri.length());
} else if (method.equals("POST")) {
HttpPost httpPost = (HttpPost) request;// 强转httppost请求
HttpEntity entity = httpPost.getEntity();// 获取实体
try {
params = EntityUtils.toString(entity);// 解析实体
EntityUtils.consume(entity);// 确保实体消耗
} catch (ParseException e) {
output("解析响应实体异常!", e);
} catch (IOException e) {
output("解析响应实体时java IO 异常!", e);
} catch (UnsupportedOperationException e) {
params = "entity类型:" + entity.getClass();
output("不被支持的entity 类型!", e);
}
}
info.put("params", params);
return info;
}下面是加载 httpclient 对象的方法:
public static CloseableHttpClient httpClient = getCloseableHttpClients();
/**
* 获取httpclient对象
*
* @return 返回HTTPclient对象
*/
public static CloseableHttpClient getCloseableHttpClients() {
return HttpClients.createDefault();
}


末了再次宣传一下自己的 QQ群:群号:340964272。

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