- 浏览: 1128600 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (1055)
- quartz定时任务 (1)
- json (9)
- 接口 (1)
- http (1)
- sccket (2)
- xmlbean (1)
- webservice (1)
- flex (1)
- sitemesh (2)
- json组装 (2)
- 存储过程 (6)
- ajax后台返回前台上下问 (3)
- flect反射机制 (1)
- 页面列表 (1)
- oracal结果集合并 (1)
- lucene (1)
- 读取配置文件工具 (1)
- 框架整合 (1)
- jms (3)
- 断点续传 (1)
- 页面之间的传值 (1)
- jpa (6)
- sql (8)
- jsp跳转 (1)
- jsp (6)
- jquery (2)
- ui (1)
- js与jsp之间的值的交互应用 (1)
- js空值判断 (1)
- Ajax (9)
- web-inf 编译目录 (1)
- 多线程 (9)
- 资料 (0)
- oracal (4)
- 多线程webservice (1)
- ztree (1)
- 加载与内容的变化 (1)
- 页面的公用变量 (1)
- web-inf目录结构 (1)
- 登陆系列 (1)
- jass应用于webservice认证 (2)
- 路径问题 (1)
- list合并 (1)
- list map中的value获取 (2)
- 标签tag (4)
- 方法 (1)
- 树形数据及其渲染 (1)
- require js 回调 (1)
- tab 页面切换 (2)
- 计时获取验证码 (1)
- 模式 (6)
- easyui (3)
- dialog (2)
- 乱码问题 (1)
- spring (29)
- sqlserver (1)
- iis,netframework (0)
- iis (1)
- netframework (1)
- 处理乱码问题 (1)
- struts-ajax (0)
- ,理论,了;,; (0)
- 排错方法 (1)
- hibernate (1)
- 二级缓存 (1)
- portal (1)
- date类型 (0)
- jvm out of memery StackOverflowError (1)
- echart数据填充 (0)
- echart (1)
- jmv (1)
- 学习 (0)
- java基础 (1)
- oracle性能优化 (1)
- 数据库三范式 (1)
- easy UI (1)
- oracle11g (1)
- form (3)
- servlet (2)
- spring mvc (1)
- htm5 (0)
- ibatise (1)
- 序列化 (1)
- tomcat双认证 (1)
- maven Lib (1)
- tomcat eclipse (2)
- ehcache (1)
- http 代替 ajax (2)
- rest (6)
- script脚本占位模板 (1)
- strust 标签 el表达式 (1)
- js bo (1)
- 公司资料 (0)
- js return (1)
- spring 第三方插件的工具类 (1)
- linux (10)
- linux 克隆 (1)
- linux xshell连接 (1)
- yum expect (1)
- linux 应用命令 (1)
- yum 缓存rmp包 (1)
- yum 本地库离线安装 (2)
- yum错误 (1)
- jsp页面用定时调用 (1)
- ajax setup (2)
- Exception,RuntimeException (1)
- 对话框 dialog (1)
- maven (17)
- PropertyPlaceholderConfigurer properties文件 (1)
- 错误集 (1)
- mybatise (0)
- 拦截器filter (1)
- http get post 区别 (1)
- rest 客户端两种返回的数据处理方式 (1)
- listener (2)
- maven工程 (1)
- ContainerResponseFilter (1)
- ajax action 打印任意实体类jsp (1)
- yum svn mvn (1)
- 分页 (1)
- angularjs (1)
- memcached (1)
- git (12)
- yyyyyyyy (0)
- oracal安装 (4)
- jaxwswebservice (1)
- spring bean (1)
- 排方法 (0)
- java 生成pdf (2)
- 创建目录 (1)
- 下载与生产pdf文件 (1)
- base64 (2)
- 配置文件 (2)
- blob (1)
- pdf (1)
- yum linux 安装Oracle (1)
- excl 插入数据库 (1)
- 搭建框架 (1)
- .classpath和jdk jre (1)
- mybatise 配置文件通配 (1)
- 用Maven插件生成Mybatis代码 (2)
- springmvc值的传递 (1)
- js jsp html (1)
- ajax跨域 (1)
- javamail (0)
- 提交复杂格式json数据 (1)
- get中文乱码/post (1)
- 弹出框,承载弹出链接----页面,显示大图 (1)
- @RequestBody list bean (1)
- 隐藏域 (1)
- 多页保存 (1)
- form 校验 (1)
- 注册,上传图片 (1)
- 登录验证 (1)
- 全局的异常处理 (0)
- 异常捕获,显示在页面 (0)
- mybatise事物配置 (1)
- maven compile (1)
- 时间格式 (1)
- js 跳转页面 (1)
- pringsecurity 角色授资源要重启服务 (0)
- Retrofi restfull (1)
- session过期推出,直接点击退出,退出 (0)
- 参数放于requestbody (1)
- maven本地仓库jar包 (1)
- 编译环境出错jdk1.6 1,7 (1)
- jsonarray ---json数组格式 (1)
- java后台文件上传,接受的2种方式 (0)
- 生成保存图片 (1)
- 权限mysql数据库Md5加密sql (1)
- mysql一对多关联查询 (1)
- mysql批量更新 (0)
- oracle in exists 区别 (1)
- https (1)
- linux发布脚本 (1)
- dubbo zookeepr (1)
- request.getParameter() (1)
- request.setAttribute() (1)
- @RequestMapping @ResponseBody (1)
- @RequestMapping @responsebody src控件 后台如何写入src值 (1)
- dwz (8)
- lib jar maven (1)
- web服务访问名称 (1)
- mvc返回内容设置,拦截 (1)
- @ResponseBody 返回json处理 (1)
- 视图,函数,存储过程 (1)
- <context:annotation-config/> (1)
- <context:component-scan/> (1)
- xml路劲通配 (2)
- 杂项 (1)
- dubbo (34)
- redis (25)
- mybatis (34)
- springmvc (15)
- js (7)
- sprinvmvc (1)
- 设计理念 (1)
- 工程 (1)
- 其他 (149)
- 导出,下载 (1)
- session (4)
- token (1)
- Exception处理 (2)
- 注解 (2)
- 框架 (3)
- shrio (1)
- login (1)
- 项目结构设计 (1)
- mybatis两种关联查询 (1)
- mybaits (2)
- 迭代模式 (1)
- oralce树形数据结构构建 (2)
- 树形结构的jsp展现 (1)
- filter intecept(Struts) (1)
- 树形结构数据的提交 (1)
- @RequestBody @RequestParam (1)
- div (1)
- equals重写 (1)
- 程序设计 (1)
- f多层for循环跳出 (1)
- 看源码 (0)
- 权限系统普遍通性 (1)
- 设计程序 (1)
- 动态拼接元素样式问题 (1)
- sql迭代 (1)
- debug断点 (1)
- spring mvc 扫描注解(ioc (1)
- di) (1)
- jdk (2)
- cglib (1)
- mybatis 多层括号(超过三层)解析不了 (1)
- tiles (2)
- cacheManager缓存的切换 (1)
- jsp,xml中el表达式等占位符中的数据操作 (1)
- jpa 及spring data jpa开发 (1)
- compareTo equals toString (1)
- 子页面用父页面js (1)
- jsp相对路径自加问题 (1)
- bean之间的相互拷贝 (1)
- DECODE (2)
- 泛型 (2)
- NVL (1)
- jsp jstl函数 用标签声明页面变量,供jstl使用,时间格式问题 (1)
- form表单切换action值 (1)
- response.getWriter().write()功能优于springMvc的返回 (1)
- 快速复制构建项目 (1)
- activeMq (15)
- cache (2)
- sql获取序列号 (1)
- 上传 (2)
- tfs (1)
- jsp标签 (2)
- qita (1)
- 触发器 (1)
- Exception (1)
- mybais (1)
- 标签 (1)
- connect by (1)
- for ... in (1)
- map转化为list (1)
- 树形结构list构建(树形实体) (1)
- 左侧菜单的设计 (1)
- response.getWriter().write() (1)
- eclipse打断点之后断无效 (1)
- 直接访问/web-inf/下的页面 (1)
- clob (1)
- freemark (1)
- 框架的设计 (1)
- get方式处理乱码 (1)
- Request的getParameter和getAttribute方法的区别 (1)
- cas (9)
- 时间格式问题 (1)
- ResponseUtil.writeToResponse (1)
- 树形数据的反选 (1)
- spring data jpa (1)
- jsp异常提示 (1)
- jquery js (1)
- eclipse (1)
- 乱码 (1)
- Json OBJETC (1)
- PROCEDURE (1)
- pl/sql oracle (1)
- 设计 (1)
- el表达式 (3)
- iframe (1)
- map (1)
- jsp中调用Java (1)
- response.getWriter().write() ajax (1)
- mybatis xml 传入参数 (0)
- response与request在返回时作用区别 (1)
- spring cache (1)
- 模型驱动 (1)
- 关于mybatis传空值的处理 (1)
- 日志配置 (1)
- mapper (1)
- mapper mybatis (1)
- mapper mybatis-spring spring-data-jpa (1)
- js插件 (1)
- spring-data-jpa (2)
- 字节流转化过程 (1)
- 数据库 (11)
- jsp页面 (1)
- 局域网络访问问题 (1)
- plsql (2)
- response (1)
- plsq (1)
- Proxool (1)
- cas security (1)
- 系统配置化 (1)
- 集群 (4)
- springboot (24)
- 设计模式 (5)
- 通知 (1)
- 架构 (48)
- zookeeper (5)
- mvc框架 (1)
- 事物隔离策略 (1)
- jvm (8)
- 调研 (1)
- Java工具类 (1)
- 并发容器 (3)
- 多线程管理器 (4)
- 简历 (0)
- 查询 (1)
- 集群工具 (1)
- springMcv (1)
- ConcurrentHashMap (1)
- hashtable (1)
- cac (1)
- 树形结构 (1)
- 定时任务 (1)
- tortoiseGit (2)
- struts (11)
- shiro (31)
- log4j (3)
- struts2 (2)
- 编码 (1)
- request (3)
- Nginx (14)
- tomcat (1)
- idea (12)
- mvc (2)
- BeanUtils (2)
- image (1)
- mino (1)
- httpClient (1)
- volecity (1)
- swagger (3)
- 调错 (0)
- data (1)
- log (1)
- shell (1)
- 事物 (3)
- junit (1)
- RestTemplate (2)
- 线程 (0)
- Exception异常处理 (1)
- Exception异常注解 (1)
- lock (1)
- HashMap (1)
- 面试 (0)
- rabbitMq (1)
- rainCat (1)
- 其它 (1)
- activemq消息传送机制以及ACK机制详解 (0)
- mysql (7)
- fildder (1)
- UML (1)
- 校验 (1)
- 反射 (1)
- 切面 (1)
- springioc (1)
- urule2 (0)
- skywalking (1)
- urule (2)
- docker (2)
- 前端 (1)
- bootstrap (1)
- eureka (2)
- springcloud (16)
- jenkins (2)
- springsecurity (1)
- 数据结构 (4)
- gradle (1)
- mycat (3)
- nacos (1)
- canary (1)
- 线程池 (1)
- solr (1)
- resteasy (2)
- BI (1)
- dfs (2)
- elasticsearch (1)
- ruby (1)
- logstash (1)
- clickhouse (2)
- davinci (15)
- java (1)
- davinvi (1)
- fastdfs (1)
- vue (1)
- 《将博客搬至CSDN》 (1)
最新评论
-
nizhipeng123:
private SessionFactory sessio ...
用map接收参数的几个注意的问题
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;
}
用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;
}
相关推荐
AJAX(Asynchronous JavaScript and XML)的核心是利用JavaScript进行异步通信,XML最初是用来传输数据的格式,但现在更多地使用JSON来代替。 ### AJAX文件上传原理 1. **创建XMLHttpRequest对象**:在所有现代...
**Ajax基本原理** Ajax,全称为Asynchronous JavaScript + XML,是一种在无需刷新整个网页的情况下,能够更新部分网页内容的技术。最初由Jesse James Garrett提出,它并非一项全新的技术,而是结合了JavaScript、...
在本文中,我们将深入探讨Ajax的核心概念、工作原理以及如何使用JavaScript库Prototype来实现Ajax请求。 Ajax的核心思想是利用JavaScript创建异步通信(XMLHttpRequest对象),通过这个对象与服务器进行数据交换,...
Ajax(Asynchronous JavaScript and XML)是一种...通过理解和掌握Ajax的基本原理和使用,开发者可以创建更动态、响应更快的网页应用。在学习过程中,实践是关键,通过不断尝试和调试,可以更好地理解Ajax的工作机制。
5. **JSON(JavaScript Object Notation)**:代替XML作为数据交换格式,由于其简洁性和易用性,逐渐成为AJAX应用中的首选。 **AJAX工作原理:** 1. 用户触发事件,例如点击按钮。 2. JavaScript代码创建一个新的...
2. **JSON代替XML**:现在更常用JSON格式传输数据,因为它的解析速度更快,结构更简单。 3. **HTML5的History API**:通过pushState和replaceState方法,可以更新浏览器的历史记录和URL,解决前进/后退问题。 4. **...
尽管如此,了解其原理和过去的技术仍然是有价值的,尤其是对于学习和理解Web开发中的AJAX(Asynchronous JavaScript and XML)技术以及API接口设计。 1. **AJAX基础** AJAX的核心在于能够在不刷新整个页面的情况下...
- **原理**:通过Ajax技术实现树形结构的动态加载,即只在需要时才向服务器请求数据。 - **技术细节**: - **XMLHttpRequest**:用于异步获取数据。 - **JavaScript**:处理服务器返回的数据,更新DOM元素。 - ...
AJAX技术的核心是异步Http请求操作,使用XmlHttpRequest工具代替浏览器向服务器发出Get/Post请求,然后从服务器取回必要的数据。XML标记语言也发挥了不可替代的作用,用于解析和使用返回的数据。 在数字图书馆中,...
学习和理解Ajax-B项目,可以深入掌握AJAX的基本工作原理,包括异步请求、数据交换格式、以及客户端和服务器之间的通信机制。这对于开发高效、用户体验良好的Web应用至关重要。同时,也可以从中了解到如何在实际项目...
首先,Ajax的核心原理是通过JavaScript与服务器进行异步通信,XML最初是数据交换格式,但现在更多地使用JSON(JavaScript Object Notation)代替。在.NET中,我们可以使用多种框架和库来实现Ajax功能,例如: 1. **...
本教程将面向初学者,帮助理解AJAX的基本概念、工作原理以及如何在实际项目中应用。 ### 1. AJAX 的基本概念 AJAX 不是单一的技术,而是一组用于创建动态、交互性网站的技术集合。主要包括以下几个核心组成部分: ...
2. JSON数据格式:Ajax常用的数据交换格式,用于代替XML,因为JSON更轻量级且易于解析。 3. DOM操作:接收到服务器响应后,需要更新DOM以反映数据变化。掌握选择元素、创建元素和修改元素的方法至关重要。 4. 异步...
在Ajax中,JSON常用来代替XML传输数据,因为它的结构更接近JavaScript对象,处理起来更方便。 ### 3. DOM操作 Ajax更新页面通常涉及对DOM(Document Object Model)的操作。DOM是HTML和XML文档的编程接口,通过...
**Ajax(Asynchronous JavaScript and XML)技术是一种在...通过这个练习,你将深入理解Ajax的工作原理,如何发起请求、处理响应,以及如何与Java后端配合完成数据交互。不断实践和优化,将有助于提升你的Web开发技能。
- 在现代的AJAX应用中,通常使用JSON代替XML,因为JSON结构更简单,解析更快,与JavaScript的兼容性更好。 **4. AJAX的局限性** - **浏览器兼容性**:虽然现代浏览器都支持AJAX,但老版本或非主流浏览器可能存在...
1. **使用JSON代替XML**:虽然Ajax名称中有XML,但实际开发中,JSON更常用于数据交换,因为它结构简单,易于解析。 2. **避免阻塞UI**:Ajax请求是异步的,但处理返回数据时应避免阻塞用户界面,可使用Promise或...
### 一、Ajax的基本工作原理 1. **创建XMLHttpRequest对象**:这是Ajax的核心组件,几乎所有的现代浏览器都内置了这个对象,用于与服务器进行通信。 2. **打开连接**:使用XMLHttpRequest对象的`open()`方法,指定...
- **JSON与AJAX结合**:在现代AJAX应用中,通常使用JSON代替XML传输数据,因为JSON与JavaScript对象直接对应,解析和序列化更方便。 ### 4. jQuery和AJAX库 - **jQuery**:一个广泛使用的JavaScript库,简化了DOM...