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

JAVA接口连接-httpClient

2015-12-30 09:17 621 查看
客户端使用httpclient发送请求:相比于jdk自带的URLConnection,增加了易用性和灵活性,它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性

客户端处理:

1.使用PostMethod方式

将文件封装到FilePart中,放入Part数组,同时,其他参数可以放入StringPart中,这里没有写,只是单纯的将参数以setParameter的方式进行设置。此处的HttpClient是org.apache.commons.httpclient.HttpClient。

public void uploadForPostMethod(){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(uri);
try {
//使用setParameter设置参数,模拟页面提交
postMethod.setParameter("name","张三");
postMethod.setParameter("age", "16");
Part[] parts = { new FilePart(file.getName(), file) };
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
//设置连接超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
//设置读取数据超时时间
httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000);
//执行postMethod请求
httpClient.executeMethod(postMethod);//此方法返回一个int类型的status值,可以根据此值判断是否传值成功
String response = postMethod.getResponseBodyAsString();
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}finally{
//释放连接
postMethod.releaseConnection();
}
}


2.使用httpPost方式

与上面类似,只不过变成了FileBody。上面的Part数组在这里对应HttpEntity。此处的HttpClient是org.apache.http.client.methods下的。

public void uploadForHttpPost(){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
// 把一个普通参数和文件上传给下面这个地址,是一个servlet
HttpPost httpPost = new HttpPost(uri);
//把文件对象转换为流对象,依赖于jar包
FileBody bin = new FileBody(new File(localFile));
StringBody userName = new StringBody("Scott", ContentType.create(
"text/plain", Consts.UTF_8));
StringBody password = new StringBody("123456", ContentType.create(
"text/plain", Consts.UTF_8));
HttpEntity reqEntity = MultipartEntityBuilder.create()
// 相当于<input type="file" name="file"/>
.addPart("file", bin)

// 相当于<input type="text" name="userName" value=userName>
.addPart("userName", userName)
.addPart("pass", password)
.build();
httpPost.setEntity(reqEntity);
// 发起请求 并返回请求的响应
response = httpClient.execute(httpPost);
System.out.println("The response value of token:" + response.getFirstHeader("token"));
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
System.out.println("Response content length: " + resEntity.getContentLength());
// 打印响应内容
System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
}
// 销毁
EntityUtils.consume(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
}


官网所采用HttpClient发送客户端请求的例子:使用PostMethod方式

HttpClient httpClient = new HttpClient();
// 设置超时时间
HttpConnectionManagerParams managerParams = httpClient
.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(60000);
// 设置读数据超时时间(单位毫秒)
managerParams.setSoTimeout(60000);*/
//设置编码格式
httpClient.getParams().setContentCharset("UTF-8");
//类似一种http协议
Protocol myhttps = new Protocol("https",
new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
//构造PostMethod的实例 eleOrderUrl从配置文件中读取
elcOrderUrl = FileUtil.getInstance().getServerUrlForElcOrder();
PostMethod postMethod = new PostMethod(elcOrderUrl);
//请求参数
String dayAfter = null;
if(elcOrderQuery.getEndTime()!=null && !"".equals(elcOrderQuery.getEndTime())){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(elcOrderQuery.getEndTime());
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day+1);

dayAfter=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());

}
//
JSONObject jsonObj = new JSONObject();
jsonObj.put("userName", elcOrderQuery.getUserName());
jsonObj.put("startTime", elcOrderQuery.getStartTime());
jsonObj.put("endTime", dayAfter);
jsonObj.put("orderNumbers", elcOrderQuery.getOrderNumbers());
jsonObj.put("conName", elcOrderQuery.getConName());
jsonObj.put("cargoName", elcOrderQuery.getCargoName());
jsonObj.put("acceptStatus", elcOrderQuery.getAcceptStatus());
jsonObj.put("startLine", elcOrderQuery.getStartLine());
jsonObj.put("limit", elcOrderQuery.getLimit());
String js = jsonObj.toString();
RequestEntity entity = new StringRequestEntity(js,
"application/json", "UTF-8");
postMethod.setRequestEntity(entity);
postMethod.addRequestHeader("Content-Type",
"application/json;charset=UTF-8");
// 执行postMethod
httpClient.executeMethod(postMethod);
String responseBody = postMethod.getResponseBodyAsString();
Map<String, Class> classMap = new HashMap<String, Class>();

classMap.put("elcOrderList", ElcOrder.class);
ElcOrderPage elcOrderPage = (ElcOrderPage) net.sf.json.JSONObject.toBean(net.sf.json.JSONObject.fromObject(responseBody), ElcOrderPage.class,classMap);
return elcOrderPage;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java