httpclient模拟服务器请求

// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = //new HttpPost("http://crmetl.yishenghuo.com:8142/outserver/startUpByHand.htm");
new HttpPost("http://localhost:8087/outserver/startUpByHand.htm");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("userName", "admin"));
formparams.add(new BasicNameValuePair("passWord", "123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) formparams, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
try {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
//0:更新成功,1:更新失败,2:更新中,3:距离上次更新不足1个小时
JSONObject json = new JSONObject();
if("0".equals(entity)){
json.put("code", "0");
json.put("message", "更新成功!");
}else if("1".equals(entity)){
json.put("code", "1");
json.put("message", entity+"更新失败!");
}else if("2".equals(entity)){
json.put("code", "2");
json.put("message", entity+"更新中!");
}else if("3".equals(entity)){
json.put("code", "3");
json.put("message", entity+"距离上次更新不足1个小时,请稍候再更新。");
}
json.put("message", "未知错误。。。");
response.getWriter().print(json.toJSONString());
logger.info("更新结果:"+EntityUtils.toString(entity, "UTF-8"));

}
} finally {
httpResponse.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

posted @ 2015-10-21 17:18  萧雪痕  阅读(328)  评论(0编辑  收藏  举报