//http请求 body内容添加
public static void do_json_req(){
HttpPost request = new HttpPost("http://localhost:8080/DSQ_Payment/uccb.do");
JSONObject param_data = new JSONObject();
param_data.put("orderId", "abcf1330");
param_data.put("gameId", 123);
param_data.put("accountId", "12221222211123");
param_data.put("creator", "JY");
param_data.put("payWay", 1);
param_data.put("amount", "100.00");
param_data.put("callbackInfo", "custominfo=xxxxx#user=xxxx");
param_data.put("orderStatus", "S");
param_data.put("failedDesc", "");
param_data.put("cpOrderId", "1234567");
JSONObject param = new JSONObject();
param.put("ver", "2.0");
param.put("data", param_data);
param.put("sign", "6362e564f832d2e8bbcbd50e75409d47");
// 绑定到请求Entry
StringEntity se;
try {
se = new StringEntity(param.toString());
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
String retSrc = EntityUtils.toString(httpResponse.getEntity());
// 生成 JSON 对象
// JSONObject result = new JSONObject( retSrc);
// String token = result.get("token");
System.out.println(retSrc);
} catch (Exception e) {
e.printStackTrace();
}
//http body内容接收
public String ucCB(HttpServletRequest req){
UcpayCBVO uccbvo=null;
String ret = "error....";
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line = "";
String reqstr = "";
while((line=bf.readLine()) != null){
reqstr += line;
}
if(null != reqstr && !"".equals(reqstr)){
Map<String, Object> f_map =PayUtil.jsonToMap(reqstr);
Map<String, Object> map_json =(Map<String, Object>)f_map.get("data");
map_json.put("ver", f_map.get("ver"));
map_json.put("sign", f_map.get("sign"));
reqstr=PayUtil.ObjectToJsonStr(map_json);
uccbvo = (UcpayCBVO) PayUtil.jsonToObject(reqstr, UcpayCBVO.class);
ret = ucService.callBackPayCenter(uccbvo);
}
log.debug("uccb: " + PayUtil.ObjectToJsonStr(uccbvo));
} catch (Exception e) {
log.error("uc cb error!", e);
}
log.debug("uc cb ret=" + ret + "; orderid=" + uccbvo.getOrderId());
return ret;
}
不是全部的代码,留下主要的两部分,给以后做参考~~
以下是HttpClient不同版本超时时间的设置
3.X是这样的
HttpClient client=new DefaultHttpClient();client.setConnectionTimeout(30000); client.setTimeout(30000);HttpClient httpClient=new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet=new HttpGet("http://www.baidu.com");//HTTP
Get请求(POST雷同)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间httpGet.setConfig(requestConfig);httpClient.execute(httpGet);//执行请求
本文介绍了一种使用Java实现的HTTP请求与响应处理方法,包括如何构造带有JSON体的POST请求,以及如何解析HTTP响应中的JSON数据。同时,还提供了不同版本的HttpClient设置超时时间的方法。
1699

被折叠的 条评论
为什么被折叠?



