ajax主要用于系统内部方法的发起
用httpClient 后台模拟ajax主要是针对rest接口的数据调用
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
HttpClient更方便更强大的解决了HttpURLConnection能做到或者不能做到的事情,HttpClient模块提供的两大类HttpPost和HttpGet实现Http请求:
HttpPost —— 传送的数据量较大,一般被默认为不受限制。一般用于发送一些表单数据,传输数据更安全
HttpGet —— 传送的数据量较小,不能大于2KB。一般用于请求获取一些信息,执行效率更高
其中的认证信息就是通过setheader();来实现的
method.setHeader("X-Auth-Token", token);
// 记录日志需要的参数
if (isPostInfo) {
method.setHeader("Event-Id", UUID.randomUUID().toString());
method.setHeader("User-Id", CommonUtil.getUserId());
}
method.setHeader("Content-Type", "application/Json");
原理解析:
/**
* POST请求,上传表单
* @param url 链接地址“http://host:8080/Login.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
*/
public static String postTableData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
String result = null;HttpClient httpclient = createHttpClient();// 创建一个HttpClient
HttpPost httppost = new HttpPost(url);// 创建一个POST请求
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));// 添加请求参数到请求对象
httppost.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识 ,报文头不是url之后的参数,只是用于表识的东西,类似于action空间名
HttpResponse response = httpclient.execute(httppost);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
/**
* Get请求,下载数据
* @param url 链接地址“http://host:8080/GetList.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
* /
public static String getListData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
// 构建url
if (params != null) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < params.size(); i++) {
buf.append("&").append(params.get(i).getName()).append("=").append(params.get(i).getValue());
}
if (url.indexOf("?") != -1)// url已经有参数
{
url = url + buf.toString();
} else {
url = url + "?" + buf.toString();
}
}
String result = null; HttpClient httpclient = createHttpClient();// 创建一个HttpClient
HttpGet httpGet = new HttpGet(url);// 创建一个Get请求
httpGet.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识
HttpResponse response = httpclient.execute(httpGet);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
//调用代码:
传入的调用对方rest的方法参数
String resultJson = JSONObject.toJSON(instance).toString();
HttpClientPostRequest postRequest = new HttpClientPostRequest(ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/nsrs/instantiate");
//传入参数,并获取对方接口返回值
String result = postRequest.processPostEntity(resultJson, true);
JSONObject jsonObj = JSONObject.parseObject(result);
ResponseVO resVO = (ResponseVO) JSONObject.toJavaObject(jsonObj, ResponseVO.class);
//具体实现代码:
方式(一):
HttpClient httpClient = new DefaultHttpClient();
//获取方法类型post get
HttpPost method = new HttpPost(url);
HttpResponse response = httpClient.execute(method);
/**
*
* @Title 函数名称: processPostEntity
* @Description 功能描述: 创建实例 需要post一个 entity的json(String)格式
* @param 参 数:
* @return 返 回 值: String
* @throws
*/
@SuppressWarnings({ "resource", "deprecation" })
public String processPostEntity(String entityJson, boolean isPostInfo) {
String token = CommonUtil.getAuthToken();
StringBuffer result = new StringBuffer();
HttpClient httpClient = new DefaultHttpClient();
//获取方法类型post get
HttpPost method = new HttpPost(url);
if (method != null) {
try {
// 添加参数 类似于ajax的参数,传进来的参数已经是json字符串了
method.setEntity(new StringEntity(entityJson, HTTP.UTF_8));
method.setHeader("X-Auth-Token", token);
// 记录日志需要的参数
if (isPostInfo) {
method.setHeader("Event-Id", UUID.randomUUID().toString());
method.setHeader("User-Id", CommonUtil.getUserId());
}
method.setHeader("Content-Type", "application/Json");
// 设置编码 模拟浏览器发出http url请求,并转化返回结果的编码方式,执行url中的响应mvc方法,从而调用对方的rest接口
HttpResponse response = httpClient.execute(method);
//对方返回的另一种实体结果
InputStream in = response.getEntity().getContent();
BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String st = breader.readLine();
result.append(st);
while (st != null) {
st = breader.readLine();
}
int statusCode = response.getStatusLine().getStatusCode();
logger.info("statusCode:" + statusCode);
} catch (IOException e) {
// 发生网络异常
logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
} finally {
method.abort();
}
}
return result.toString();
}
方式(二):
实现原理:
HttpClient httpClient = new HttpClient();
HttpMethod httpMethod = new DeleteMethod(url);
// HttpMethod httpMethod = new GetMethod(url);
httpClient.executeMethod(httpMethod);
调用实例:
public ResultModel<List<TplInsVO>> getInsList(int page, int rows, String sortName, String sortType) {
logger.info("查询实例信息 " + "页码:" + page + "记录数:" + rows + "排序字段:" + sortName + " 排序方式:" + sortType);
final List<TplInsVO> voList = new ArrayList<TplInsVO>();
// 调用REST 接口
String requestUrl = ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/nsrs/";// http://172.16.38.132:8080/nfvo/rest/nsrs
HttpClientRequest request = new HttpClientGetRequest(requestUrl);
// 分页信息
request.addParam("pageSize", page);
request.addParam("pageNum", rows);
request.addParam("orderField", sortName == null ? "" : sortName);
request.addParam("orderType", sortType == null ? "" : sortType);
try {
request.process(new HttpClientResponseHandler() {
@Override
public void handle(String response, String retCode, String msg) throws HttpClientException {
logger.info("getInsList-process-return-response:" + response);
JSONObject jsonObj = JSONObject.parseObject(response);// .fromObject(response);
logger.debug("查询一组实例信息,返回状态retCode:" + retCode + ",返回信息Msg:" + msg);
NsrPageResult result = (NsrPageResult) JSONObject.toJavaObject(jsonObj.getJSONObject("result"), NsrPageResult.class);
if (result != null) {
String num = result.getSize();
List<Nsr> nsrList = result.getNsrList();
if (nsrList != null && !nsrList.isEmpty()) {
TplInsVO vo;
for (Nsr nsr : nsrList) {
vo = new TplInsVO();
vo.setInsId(nsr.getId());
vo.setInsName(nsr.getName());
vo.setNsdId(nsr.getNsdId());
vo.setInsStatus(changeStatus(nsr.getStatus()));
vo.setInsType(nsr.getFlavour() == null ? "" : nsr.getFlavour().getName());
vo.setIpAddr(nsr.getIpAddr());
voList.add(vo);
}
}
}
}
});
} catch (HttpClientException e) {
e.printStackTrace();
}
int totalSize = voList.size();
int toRow = (page - 1) * 10 + 10;
if (toRow > voList.size()) {
toRow = voList.size();
}
List<TplInsVO> newList = voList.subList((page - 1) * 10, toRow);
// ResultModel<List<TplInsVO>> result = new ResultModel<List<TplInsVO>>(newList);
ResultModel<List<TplInsVO>> result = new ResultModel<List<TplInsVO>>(voList);
result.setResult(Constants.RESULT_FLAG.SUCCESS.number());
result.setTotalSize(totalSize);
result.setCurrentPageNum(page);
result.setPageSize(rows);
result.setStartRowNo(CommonUtil.getStartRowNo(page, rows));
return result;
}
/**
* 执行请求
* @throws HttpClientException httpClient请求异常
*/
@Override
public int process(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException {
String auth_token = null;
try {
auth_token = CommonUtil.getAuthToken();
} catch (Exception e) {
e.printStackTrace();
}
// 获取子类的具体的HttpMethod实现
HttpMethod httpMethod = this.getHttpMethod();
// Head 里面塞值 -- modify by renjing
// --- X-Auth-Token 值取什么?
logger.info("client auth_token=" + auth_token);
Header header = new Header("X-Auth-Token", auth_token);
httpMethod.setRequestHeader(header);
if (ObjectUtils.isNull(httpMethod))
throw new NullPointerException("Cannot process request because the httpMethod is null.");
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
try {
long start = System.currentTimeMillis();
logger.info("Begin to visit {}.", httpMethod.getURI());
httpClient.executeMethod(httpMethod);
logger.info("End to visit and take: {} ms.", (System.currentTimeMillis() - start));
} catch (IOException e) {
throw new HttpClientException(httpMethod.getPath(), e.getMessage());
}
// 利用HttpClientResponseHandler处理响应结果
String retCode = null;
String msg = null;
if (ObjectUtils.isNotNull(httpClientResponseHandler))
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream()));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
String response = builder.toString();
// httpClientResponseHandler.handle(response); 把返回的response,作为流的方式读出,作为一个json格式的对象返回(不是实体类的格式)
JSONObject jsonObj = JSONObject.parseObject(response);// .fromObject(response);
retCode = jsonObj.getString("retCode");
msg = jsonObj.getString("msg");
httpClientResponseHandler.handle(response, retCode, msg);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
httpMethod.releaseConnection();
/* if (retCode == null || !retCode.equals("ok")) {
throw new RuntimeException(msg);
} else {
return 0;
}*/
return 0;
}
/**
* 执行请求
* @throws HttpClientException httpClient请求异常 需要记录日志
*/
@Override
public int processAndSaveLog(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException {
String auth_token = null;
try {
auth_token = CommonUtil.getAuthToken();
} catch (Exception e) {
e.printStackTrace();
}
// 获取子类的具体的HttpMethod实现
HttpMethod httpMethod = this.getHttpMethod();
// Head 里面塞值 -- modify by renjing
// --- X-Auth-Token 值取什么?
logger.info("client auth_token=" + auth_token);
// Header header = new Header("X-Auth-Token", auth_token);
httpMethod.addRequestHeader("X-Auth-Token", auth_token);
httpMethod.addRequestHeader("Event-Id", UUID.randomUUID().toString());
httpMethod.addRequestHeader("User-Id", CommonUtil.getUserId());
if (ObjectUtils.isNull(httpMethod))
throw new NullPointerException("Cannot process request because the httpMethod is null.");
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
try {
long start = System.currentTimeMillis();
logger.info("Begin to visit {}.", httpMethod.getURI());
//模拟浏览器发出http url 请求,url中有需要调用方法的mvc自此完成方法的执行
httpClient.executeMethod(httpMethod);
logger.info("End to visit and take: {} ms.", (System.currentTimeMillis() - start));
} catch (IOException e) {
throw new HttpClientException(httpMethod.getPath(), e.getMessage());
}
// 利用HttpClientResponseHandler处理响应结果
String retCode = null;
String msg = null;
if (ObjectUtils.isNotNull(httpClientResponseHandler))
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream()));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
String response = builder.toString();
// httpClientResponseHandler.handle(response);
JSONObject jsonObj = JSONObject.parseObject(response);// .fromObject(response);
retCode = jsonObj.getString("retCode");
msg = jsonObj.getString("msg");
httpClientResponseHandler.handle(response, retCode, msg);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
httpMethod.releaseConnection();
/* if (retCode == null || !retCode.equals("ok")) {
throw new RuntimeException(msg);
} else {
return 0;
}*/
return 0;
}
//对应这个的解析getHttpMethod
String requestUrl = ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/nsrs/";// http://172.16.38.132:8080/nfvo/rest/nsrs
HttpClientRequest request = new HttpClientGetRequest(requestUrl);
// 分页信息
request.addParam("pageSize", page);
request.addParam("pageNum", rows);
request.addParam("orderField", sortName == null ? "" : sortName);
request.addParam("orderType", sortType == null ? "" : sortType);
========================
@Override
public HttpMethod getHttpMethod() {
StringBuilder builder = new StringBuilder();
for (Entry<String, Object> entry : params.entrySet()) {
builder.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue())).append("&");
}
String param = null;
if (builder.length() != 0)
param = builder.deleteCharAt(builder.length() - 1).toString();
String url = null;
if (StringUtils.isEmpty(param))
url = this.url;
else
url = this.url + "?" + param;
HttpMethod httpMethod = new DeleteMethod(url);
// HttpMethod httpMethod = new GetMethod(url);
return httpMethod;
}
http 代替 ajax原理解析
猜你喜欢
转载自yuhuiblog6338999322098842.iteye.com/blog/2202305
今日推荐
周排行