httpClient实例--返回响应部分并且转换成对象
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
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 com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
/**
* httpClient
* 利用apache提供的httpClient工具类,访问接口并返回response的body部分
* 并转换成对象
* */
public class StreamTest {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public static void main(String[] args) {
HttpPost httpPost = new HttpPost("http://10.254.60.22:8002" + "/decision/apply/queryRejectReason");
//String address = "http://10.254.60.22:8002" + "/decision/apply/queryRejectReason";
//httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(212).setConnectTimeout(112).build());
//UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
String str = "{\"identityNo\":372925198904086927}";
//StringEntity entity = new StringEntity(str,"UTF-8");
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("identityNo", "372925198904086927");
String jsonContent = GsonUtils.toJson(paramMap);
StringEntity entity = new StringEntity(jsonContent, "UTF-8");
entity.setContentType("application/json");//必须设置成json
HttpClient httpClient = new DefaultHttpClient();
httpPost.setEntity(entity);
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
//String response = HttpClientUtils.getMethodPostResponse(address,entity);
InputStream inputStream = null;
try {
inputStream = response.getEntity().getContent();
} catch (UnsupportedOperationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
try {
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] ss = out.toByteArray();
String result=null;
try {
result = new String(ss, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//打印结果:{"status":"1","msg":"获取成功","data":[{"id":91413,"idNo":"372925198904086927","prod":"CCL","dcsnTime":1479913104000,"dcsnRslt":"拒绝","rejRsn":"手机使用期限不足/月","custId":166635,"updTime":1479934476000},{"id":91414,"idNo":"372925198904086927","prod":"CCL","dcsnTime":1478800405000,"dcsnRslt":"拒绝","rejRsn":"卡龄不足且评分低","custId":167129,"updTime":1479934476000},{"id":91415,"idNo":"372925198904086927","prod":"CCL","dcsnTime":1478800405000,"dcsnRslt":"拒绝","rejRsn":"社保或公积金缴金月数不符合要求","custId":167129,"updTime":1479934476000}]}
System.out.println(result);
JSONObject json = JSONObject.parseObject(result);
String msg = json.getString("msg");
String status = json.getString("status");
String data = json.getString("data");
//System.out.println(data);
Response response1 = null;
if("[]".equals(data) || "".equals(data) || data == null){
response1 = new Response(status, msg, null);
}else{
List<DDHRejectReasonEntity> res = (List<DDHRejectReasonEntity>) GsonUtils.convertList(data, DDHRejectReasonEntity.class);
response1 = new Response(status, msg, res);
//response = GsonUtils.convertObj(respJson, Response.class);
}
}
}
/**
* 需要转换的对象
* */
class DDHRejectReasonEntity {
private Integer id; //主键
private String idNo; // 身份证号
private String prod; // 产品
private Date dcsnTime; // 决策时间
private String dcsnRslt; // 决策结果
private String rejRsn; // 拒绝原因
private Integer custId; // 客户ID
private Date updTime; // 更新时间
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getProd() {
return prod;
}
public void setProd(String prod) {
this.prod = prod;
}
public Date getDcsnTime() {
return dcsnTime;
}
public void setDcsnTime(Date dcsnTime) {
this.dcsnTime = dcsnTime;
}
public String getDcsnRslt() {
return dcsnRslt;
}
public void setDcsnRslt(String dcsnRslt) {
this.dcsnRslt = dcsnRslt;
}
public String getRejRsn() {
return rejRsn;
}
public void setRejRsn(String rejRsn) {
this.rejRsn = rejRsn;
}
public int getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public Date getUpdTime() {
return updTime;
}
public void setUpdTime(Date updTime) {
this.updTime = updTime;
}
}
class Response {
private String status;
private String msg;
private Object data;
public Response(String status, String msg, Object data) {
super();
this.status = status;
this.msg = msg;
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
/**
* 获取数据成功
* **/
public static Response successResponse(Object data) {
return new Response(BaseConstants.CommonCode.SUCCESS_CODE, BaseConstants.CommonMessage.SUCCESS_MESSAGE, data);
}
public static Response successResponse() {
return new Response(BaseConstants.CommonCode.SUCCESS_CODE, BaseConstants.CommonMessage.SUCCESS_MESSAGE, "");
}
public static Response response(String status, String msg, Object data) {
return new Response(status, msg, data);
}
public static Response response(String status) {
return new Response(status, "", "");
}
public static Response response(String status, String msg) {
return new Response(status, msg, "");
}
public static Response fail(String msg) {
return new Response(BaseConstants.CommonCode.FAILED_CODE, msg, "");
}
public static Response success(String msg) {
return new Response(BaseConstants.CommonCode.SUCCESS_CODE, msg, "");
}
public static Response fail(String msg, Object data) {
return new Response(BaseConstants.CommonCode.FAILED_CODE, msg, data);
}
public static Response success(String msg, Object data) {
return new Response(BaseConstants.CommonCode.SUCCESS_CODE, msg, data);
}
}
class GsonUtils {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public static String toJson(Object obj) {
if (obj == null) {
return "";
}
return gson.toJson(obj);
}
public static <T> List<T> convertList(String json, Class<T> cls) {
if (StringUtils.isBlank(json)) {
return new ArrayList<T>();
}
Type type = new TypeToken<List<JsonObject>>() {
}.getType();
List<JsonObject> jsonObjs = gson.fromJson(json, type);
List<T> listOfT = new ArrayList<>();
for (JsonObject jsonObj : jsonObjs) {
listOfT.add(convertObj(jsonObj.toString(), cls));
}
return listOfT;
}
public static <T> T convertObj(String json, Class<T> cls) {
if (StringUtils.isBlank(json)) {
return null;
}
return gson.fromJson(json, cls);
}
}
class BaseConstants {
//通用的状态码
public abstract class CommonCode {
public static final String FAILED_CODE = "0"; //获取数据失败状态码
public static final String SUCCESS_CODE = "1"; //获取数据成功状态码
}
//通用的消息
public abstract class CommonMessage {
public static final String FAILED_MESSAGE = "获取数据失败!"; //获取数据失败
public static final String SUCCESS_MESSAGE = "请求数据成功!"; //获取数据失败
public static final String ERROR_MESSAGE = "请求数据出错!!";
}
}
httpClient实例--返回响应部分并且转换成对象的更多相关文章
- json字符串转换成对象需要注意的问题
json转换成对象的时候应该尽量避免出现特殊的符号,如“\”这样的字符在转义成数组的时候会被去除掉,最好的例子就是后台返回的内容为存储路径的JSON,这时候最好是把一个斜杠变为两个斜杠,如: [{&q ...
- 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间
生成二维码 /// <summary>/// 生成二维码/// </summary>public static class QRcodeUtils{private static ...
- json转换成对象
在json转换成对象时,json的key会与java 类的字段一一对应.如果没有映射上的java字段会在该数据类型上填充默认值,如int 0,String null 等. 没有映射的json key在 ...
- 在一般处理程序中,把Form Post过来的表单集合转换成对象 ,仿 MVC post,反射原理
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.L ...
- json 字符串转换成对象,对象转换成json字符串
json 字符串转换成对象,对象转换成json字符串 前端: 方法一: parseJSON方法: [注意jquery版本问题] var str = '{"name":&qu ...
- Table转换成实体、Table转换成实体集合(可转换成对象和值类型)
/// <summary> /// Table转换成实体 /// </summary> /// <typeparam name="T">< ...
- request请求转换成对象。
1)前端post数据过来,key和val键值对会有很多,这个时候往后端进行插值的时候,最好将这些键值对转换成对象进行处理. 使用common-beanutils 来将前端传递过来的map直接转换成对象 ...
- JSON字符串转换成对象时候 需要有默认构造器 因为这是通过反射创建的 反射是先通过默认构造器创建对象的
JSON字符串转换成对象时候 需要有默认构造器 因为这是通过反射创建的 反射是先通过默认构造器创建对象的
- Js将字符串转换成对象或数组en
举个例子 var test='{ colkey: "col", colsinfo: "NameList" }' a.将文本转换成对象 var test='{ c ...
随机推荐
- (三)underscore.js框架Objects类API学习
keys_.keys(object) Retrieve all the names of the object's properties. _.keys({one: 1, two: 2, three ...
- MongoDB地理空间数据存储及检索
目录 1.存入地理数据 GeoJSON数据存入 1.Ponit 点数据 2.LineString 线数据(多段线) 3. Polygon 多边形数据 4.MultiPoint多点.MultiLineS ...
- 在windows命令行批量ping局域网内IP
参考了博客园Alfred Zhao的文章<Windows平台ping测试局域网所有在用IP> 在cmd命令行运行如下命令即可: ,,) -w .%i | find "回复&quo ...
- fgrep: ifcfg-ifcfg-eth0: No such file or directory
[root@localhost ~]# service network restartfgrep: ifcfg-ifcfg-eth0: No such file or directoryfgrep: ...
- 分析轮子(五)- Vector.java
注:玩的是JDK1.7版本 一: 先上类图,从类图上看和 ArrayList.java 非常相像,可查看 分析轮子(一)-ArrayList.java 二:然后看源码,发现和 ArrayList.ja ...
- Kafka#4:存储设计 分布式设计 源码分析
https://sites.google.com/a/mammatustech.com/mammatusmain/kafka-architecture/4-kafka-detailed-archite ...
- Generate google sitemap xml
方式一. XNamespace xNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; XNamespace xht ...
- nmon监控
原文:https://www.cnblogs.com/wnfindbug/p/5719181.html 一.检查安装环境 # uname –a (查看操作系统信息,所检查服务器为64位操作系统) Li ...
- Vue 创建组件的方式
Vue 创建组件的方式 2018年08月07日 11:10:56 虔诚带着决然 阅读数:1015 版权声明:本文为博主原创文章,未经博主允许不得用做其他商业活动. https://blog.csd ...
- Android Bluetooth hci 命令分析
Android在连接BLE设备的时候,遇到连接没多久就自动断开的情况.通过HCI来分析一下. BLE设备发送连接参数更新请求 3909 15:53:01.224737 TexasIns_f0:d3:4 ...