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 = "请求数据出错!!";
}
}

posted @ 2017-03-03 10:32  ding9587  阅读(9450)  评论(0编辑  收藏  举报