- 浏览: 1084716 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (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接收参数的几个注意的问题
/**
*
*/
package com.certus.util.httpClient;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import com.certus.util.CommonUtil;
/**
* @description 通过HttpClient Post请求服务器数据的Request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public class HttpClientPostRequest extends AbstractHttpClientRequest {
private Logger logger = Logger.getLogger(HttpClientPostRequest.class);
public HttpClientPostRequest(String url) {
super(url);
}
/*@Override
public HttpMethod getHttpMethod() {
NameValuePair[] pairs = new NameValuePair[this.params.size()];
NameValuePair pair = null;
String contentType = "multipart/form-data";
int i = 0;
for (Entry<String, Object> entry : params.entrySet()) {
pair = new NameValuePair(entry.getKey(), String.valueOf(entry
.getValue()));
pairs[i++] = pair;
}
PostMethod httpMethod = new PostMethod(this.url);
httpMethod.setRequestBody(pairs);
if (StringUtils.isNotEmpty(contentType))
httpMethod.setRequestHeader("Content-Type", contentType);
return httpMethod;
}*/
@Override
public HttpMethod getHttpMethod() {
/* NameValuePair[] pairs = new NameValuePair[this.params.size()];
NameValuePair pair = null;
String contentType = "";
int i = 0;
for (Entry<String, Object> entry : params.entrySet()) {
pair = new NameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
pairs[i++] = pair;
}
PostMethod httpMethod = new PostMethod(this.url);
httpMethod.setRequestBody(pairs);
if (StringUtils.isNotEmpty(contentType))
httpMethod.setRequestHeader("Content-Type", contentType);
return httpMethod;*/
return null;
}
public String processPost(InputStream input, String tempName, String userId, String token) throws HttpClientException {
String result = httpSendPIC(url, tempName, file2byte(input), userId, token);
return result;
}
/**
*
* @Title 函数名称: processPostEntity
* @Description 功能描述: 创建实例 需要post一个 entity的json(String)格式
* @param 参 数:
* @return 返 回 值: String
* @throws
*/
@SuppressWarnings({ "resource", "deprecation" })
public String processPostEntity(String entityJson) {
String token = CommonUtil.getAuthToken();
StringBuffer result = new StringBuffer();
HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
// 添加参数
method.setEntity(new StringEntity(entityJson, HTTP.UTF_8));
method.setHeader("X-Auth-Token", token);
method.setHeader("Content-Type", "application/Json");
// 设置编码
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();
}
/**
*
* @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();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
// 添加参数
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");
// 设置编码
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();
}
@SuppressWarnings({ "resource", "deprecation" })
public String processPostParam() {
String token = CommonUtil.getAuthToken();
StringBuffer result = new StringBuffer();
HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
method.setHeader("X-Auth-Token", token);
method.setHeader("Content-Type", "text/plain");
// 设置编码
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();
}
public String httpSendPIC(String url, String tplName, byte[] PostData, String userId, String token) {
StringBuffer result = new StringBuffer();
URL u = null;
HttpURLConnection con = null;
// 尝试发送请求
try {
u = new URL(url + "?nsdName=" + URLEncoder.encode(tplName, "UTF-8"));
u = new URL(url + "?nsdName=" + tplName);
// u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "multipart/form-data");
con.setRequestProperty("X-Auth-Token", token);
con.setRequestProperty("Event-Id", UUID.randomUUID().toString());
con.setRequestProperty("User-Id", userId);
con.setConnectTimeout(20000);
con.setReadTimeout(300000);
OutputStream outStream = con.getOutputStream();
outStream.write(PostData);
outStream.flush();
outStream.close();
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
// 读取返回内容
try {
InputStream in = con.getInputStream();
BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String st = breader.readLine();
result.append(st);
while (st != null) {
st = breader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
System.out.println(result.toString());
return result.toString();
}
public byte[] file2byte(InputStream input) {
byte[] data = null;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
}
========================================================
package com.certus.util.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.certus.util.CommonUtil;
/**
* @description 抽象HttpClient 请求web服务器的request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public abstract class AbstractHttpClientRequest implements HttpClientRequest {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractHttpClientRequest.class);
// 请求URL地址
protected String url;
// 请求参数
protected Map<String, Object> params;
/**
* Constructor Method With All Params
* @param url 请求URL
*/
public AbstractHttpClientRequest(String url) {
if (StringUtils.isEmpty(url))
throw new NullPointerException("Cannot constract a HttpClientRequest with empty url.");
this.url = url;
this.params = new HashMap<String, Object>();
}
/**
* 添加request参数
* @param name 参数名
* @param value 参数值
*/
public void addParam(String name, Object value) {
this.params.put(name, value);
}
/**
* 执行请求
* @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);
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());
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;
}
/**
* 子类实现返回具体的HttpMethod对象
* @return HttpMethod
*/
public abstract HttpMethod getHttpMethod();
}
================================================================
/**
*
*/
package com.certus.util.httpClient;
/**
* @descriptionHttpClient 请求web服务器的request
* @author renjing
* @tiem 2015年2月10日上午10:15:37
*/
public interface HttpClientRequest {
/**
* 添加request参数
* @param name 参数名
* @param value 参数值
*/
public void addParam(String name, Object value);
/**
* 执行request请求
* @param httpClientResponseHandler 处理响应数据handler
* @throws HttpClientException
*/
public int process(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;
public int processAndSaveLog(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;
}
=======================================
例子
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);
*
*/
package com.certus.util.httpClient;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import com.certus.util.CommonUtil;
/**
* @description 通过HttpClient Post请求服务器数据的Request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public class HttpClientPostRequest extends AbstractHttpClientRequest {
private Logger logger = Logger.getLogger(HttpClientPostRequest.class);
public HttpClientPostRequest(String url) {
super(url);
}
/*@Override
public HttpMethod getHttpMethod() {
NameValuePair[] pairs = new NameValuePair[this.params.size()];
NameValuePair pair = null;
String contentType = "multipart/form-data";
int i = 0;
for (Entry<String, Object> entry : params.entrySet()) {
pair = new NameValuePair(entry.getKey(), String.valueOf(entry
.getValue()));
pairs[i++] = pair;
}
PostMethod httpMethod = new PostMethod(this.url);
httpMethod.setRequestBody(pairs);
if (StringUtils.isNotEmpty(contentType))
httpMethod.setRequestHeader("Content-Type", contentType);
return httpMethod;
}*/
@Override
public HttpMethod getHttpMethod() {
/* NameValuePair[] pairs = new NameValuePair[this.params.size()];
NameValuePair pair = null;
String contentType = "";
int i = 0;
for (Entry<String, Object> entry : params.entrySet()) {
pair = new NameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
pairs[i++] = pair;
}
PostMethod httpMethod = new PostMethod(this.url);
httpMethod.setRequestBody(pairs);
if (StringUtils.isNotEmpty(contentType))
httpMethod.setRequestHeader("Content-Type", contentType);
return httpMethod;*/
return null;
}
public String processPost(InputStream input, String tempName, String userId, String token) throws HttpClientException {
String result = httpSendPIC(url, tempName, file2byte(input), userId, token);
return result;
}
/**
*
* @Title 函数名称: processPostEntity
* @Description 功能描述: 创建实例 需要post一个 entity的json(String)格式
* @param 参 数:
* @return 返 回 值: String
* @throws
*/
@SuppressWarnings({ "resource", "deprecation" })
public String processPostEntity(String entityJson) {
String token = CommonUtil.getAuthToken();
StringBuffer result = new StringBuffer();
HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
// 添加参数
method.setEntity(new StringEntity(entityJson, HTTP.UTF_8));
method.setHeader("X-Auth-Token", token);
method.setHeader("Content-Type", "application/Json");
// 设置编码
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();
}
/**
*
* @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();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
// 添加参数
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");
// 设置编码
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();
}
@SuppressWarnings({ "resource", "deprecation" })
public String processPostParam() {
String token = CommonUtil.getAuthToken();
StringBuffer result = new StringBuffer();
HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (method != null) {
try {
method.setHeader("X-Auth-Token", token);
method.setHeader("Content-Type", "text/plain");
// 设置编码
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();
}
public String httpSendPIC(String url, String tplName, byte[] PostData, String userId, String token) {
StringBuffer result = new StringBuffer();
URL u = null;
HttpURLConnection con = null;
// 尝试发送请求
try {
u = new URL(url + "?nsdName=" + URLEncoder.encode(tplName, "UTF-8"));
u = new URL(url + "?nsdName=" + tplName);
// u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "multipart/form-data");
con.setRequestProperty("X-Auth-Token", token);
con.setRequestProperty("Event-Id", UUID.randomUUID().toString());
con.setRequestProperty("User-Id", userId);
con.setConnectTimeout(20000);
con.setReadTimeout(300000);
OutputStream outStream = con.getOutputStream();
outStream.write(PostData);
outStream.flush();
outStream.close();
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
// 读取返回内容
try {
InputStream in = con.getInputStream();
BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String st = breader.readLine();
result.append(st);
while (st != null) {
st = breader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
System.out.println(result.toString());
return result.toString();
}
public byte[] file2byte(InputStream input) {
byte[] data = null;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
}
========================================================
package com.certus.util.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.certus.util.CommonUtil;
/**
* @description 抽象HttpClient 请求web服务器的request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public abstract class AbstractHttpClientRequest implements HttpClientRequest {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractHttpClientRequest.class);
// 请求URL地址
protected String url;
// 请求参数
protected Map<String, Object> params;
/**
* Constructor Method With All Params
* @param url 请求URL
*/
public AbstractHttpClientRequest(String url) {
if (StringUtils.isEmpty(url))
throw new NullPointerException("Cannot constract a HttpClientRequest with empty url.");
this.url = url;
this.params = new HashMap<String, Object>();
}
/**
* 添加request参数
* @param name 参数名
* @param value 参数值
*/
public void addParam(String name, Object value) {
this.params.put(name, value);
}
/**
* 执行请求
* @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);
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());
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;
}
/**
* 子类实现返回具体的HttpMethod对象
* @return HttpMethod
*/
public abstract HttpMethod getHttpMethod();
}
================================================================
/**
*
*/
package com.certus.util.httpClient;
/**
* @descriptionHttpClient 请求web服务器的request
* @author renjing
* @tiem 2015年2月10日上午10:15:37
*/
public interface HttpClientRequest {
/**
* 添加request参数
* @param name 参数名
* @param value 参数值
*/
public void addParam(String name, Object value);
/**
* 执行request请求
* @param httpClientResponseHandler 处理响应数据handler
* @throws HttpClientException
*/
public int process(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;
public int processAndSaveLog(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;
}
=======================================
例子
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);
相关推荐
AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML),该技术并不是一种新的技术,实际上是多种...现在,可以用JavaScript调用AJAX引擎来代替产生一个HTTP的用户动作,内存中的数据编辑、页面导航
// the options for this ajax request }global(true) 数据类型: Boolean 是否为当前的请求触发全局AJAX事件处理函数,默认值为true。设置为false可以防止触发像ajaxStart或ajaxStop这样的全局事件处理函数...
一个.net发送HTTP数据实体的类 按键跳转以及按Enter以不同参数提交,及其他感应事件 动态控制Page页的Head信息 SubmitOncePage:解决刷新页面造成的数据重复提交问题 SharpRewriter:javascript + xml技术利用#实现...
因pdf的容量过大分4个压缩包打包,还有一个源码另外下载。 《.NET深入体验与实战精要》作者身为从事.NET一线开发的资深开发专家,常年耕耘...15.5.14 使用视图代替跨库操作 572 15.5.15 尽量避免大事务操作 572 15.5.16...
因pdf的容量过大分4个压缩包打包,还有一个源码另外下载。 《.NET深入体验与实战精要》作者身为从事.NET一线开发的资深开发专家,常年耕耘...15.5.14 使用视图代替跨库操作 572 15.5.15 尽量避免大事务操作 572 15.5.16...
-修正了在Grid的PageIndexChange事件中不能获取SelectedRowIndexArray属性的BUG(feedback:Violet)。 -Button控件将不再自动拥有display:inline属性,如果希望两个按钮在一行显示,请为第一个按钮设置CssStyle=...
代码 $("selector").load(url,data,function(response,status,xhr)) 该方法是最简单的从服务器获取数据的方法。它几乎与 $.get(url, data, success) 等价,不同的是它不是全局函数,并且它拥有隐式的回调函数。当...
-修正了在Grid的PageIndexChange事件中不能获取SelectedRowIndexArray属性的BUG(feedback:Violet)。 -Button控件将不再自动拥有display:inline属性,如果希望两个按钮在一行显示,请为第一个按钮设置CssStyle=...
向浏览器发送InputSream对象,通常用来处理文件下载,还可用于返回AJAX数据。 16 org.apache.struts2.dispatcher.StreamResult 16 velocity 16 处理Velocity模板 16 org.apache.struts2.dispatcher.VelocityResult ...
1)改用Session代替部分Cookie储存上传功能所用到的配置数据,以便让编辑器上传更加安全。 2)修正一个文件格式上传时存在的安全性问题。 3)上传页面去掉所有input隐藏属性储存参数,改用ViewState储存,并加入ViewState...
1)去掉现在基本没法使用的插入EXCEL表格功能,改为无组件的导入EXCEL文档功能(测试中,导入excel文档必须符合数据库格式,否则导入数据将不全)。 2)更新编辑器的部分文字资源。 3)修正4号与5号字体大小一样的BUG! ...
所有这些事件都可以在一个SWFUpload实体中被调用,这意味着在这些事件对应的函数中,你可以用 this 关键字来代替引用SWFUpload实体。 + fileDialogComplete (number of files selected) - 触发条件 1. 用户...
•Lambda表达式主要作用就是代替匿名内部类的繁琐语法。它由三部分组成: –形参列表。形参列表允许省略形参类型。如果形参列表中只有一个参数,甚至连形参列表的圆括号也可以省略。 –箭头(->),必须通过...