HttpRequest请求接口
2016-02-19 12:20
363 查看
Spring mvc 框架请求
controller:
HttpRequest类:
封装HttpRequestError类:
封装HttpRequestPost类:
controller:
<span style="font-size:14px;">@RequestMapping(value = "get", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String get() { String result = StringUtils.EMPTY;// 意思是result = "" try { int userId = getIntParameter("userId"); result = HttpRequest.get(userId); } catch (Exception e) { LOG.error("====>> Controller.get error:" + e.getMessage()); result = DCDataBean.setError(); } return result; } </span>
HttpRequest类:
public class <span style="font-size:18px;">HttpRequest</span>{ private static final HttpService GET = new HttpService (SERVICE_ID, 51);//请求服务 public static String get(int userId) { ServiceParam param = new ServiceParam(); param.add("userId", userId); return HttpRequestPost.call(GET_ORDER_COUNT, param); } }
封装HttpRequestError类:
public class DCDataBean { private static final String error = "{\"status\":2, \"msg\":\"服务系统出错\",\"data\":\"[]\"}"; private int status; private String msg; private String data; public DCDataBean(int status, String msg, String data){ this.status = status; this.msg = msg; this.data = data; } public DCDataBean(){ } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public String toString() { return "{\"status\":" + status + ", \"msg\":\"" + msg + "\",\"data\":" + data + "}"; } public static String setSocketTimeoutError(){ return socketTimeoutError; } public static String setConnectTimeoutError(){ return connectTimeoutError; } public static String setConnectError(){ return connectError; } public static String setParamError(){ return paramError; } public static String setParamError(String paramName){ return String.format(paramError_params, paramName); } public static String setError(){ return error; } }
封装HttpRequestPost类:
public class <span style="font-size:18px;">HttpRequestPost</span>{ private static final Logger LOG = Logger.getLogger(DCHttpRequest.class); private static final String JSON_KEY_RET = "ret"; private static final String SYS_LOGIN_ID = "sysLoginId"; private static final String CONTENT_TYPE_KEY = "Content-Type"; private static final String USER_AGENT_KEY = "User-Agent"; private static final String CONTENT_TYPE_JSON = "application/json"; private static final String USER_AGENT_ANDROID = "androidClient"; private static final String UTF_8 = "utf-8"; /** * 设置http请求超时配置 * @param httpClient */ private static RequestConfig getCustHttpClientConfig(){ return RequestConfig.custom() .setSocketTimeout(DCServiceConfig.socketTimeout) .setConnectTimeout(DCServiceConfig.connectTimeout).build(); } /** * 设置http请求head头内容 * @param request */ private static void setHttpRequestHead(HttpRequest request){ if(request != null){ request.setHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_JSON); request.addHeader(USER_AGENT_KEY, USER_AGENT_ANDROID); } } /** * 同步数据操作 * @param service * @param param * @return 返回是否成功同步数据 */ public static boolean callAndRetrys(final DCService service, final ServiceParam param) { // 设置当前线程用户 Admin user = Sessions.getUser(); if(user != null && param != null){ param.add(SYS_LOGIN_ID, user.getId()); } String result = post(DCServiceConfig.syncUrl, service.toJSON(param).toJSONString()); JSONObject obj = JSONExUtils.isObj(result); if(obj != null){ result = obj.getString(JSON_KEY_RET); } boolean isOK = StringExUtils.getBoolean(result); if(isOK == false){ LOG.error("====>> DCHttpRequest.callAndRetrys(" + DCServiceConfig.syncUrl + ") ==>> " + service.toJSON(param) + " Synchronous data failure!!"); } return isOK; } /** * 请求接口 * @param service * @param param * @return */ public static String call(DCService service, ServiceParam param) { // 设置当前线程用户 Admin user = Sessions.getUser(); if(user != null && param != null){ param.add(SYS_LOGIN_ID, user.getId()); } JSONObject json = new JSONObject(); json.put("content", param.toString()); String url = null; String result = post(url, json.toJSONString()); if(StringUtils.isBlank(result)){ result = DCDataBean.setError(); } DCDataBean db = JSONObject.parseObject(result, DCDataBean.class); return db.toString(); } public static JSONObject callJSON(DCService service, ServiceParam param) { String res = call(service, param); return JSONObject.parseObject(res); } /** * 发起http请求(post方式) * @param urlStr * @param json * @return * @throws Exception */ private static String post(String urlStr, String json) { String result = StringUtils.EMPTY; String no = UUID.randomUUID().toString(); String logUrl = urlStr + "?data=" + json; if(LOG.isInfoEnabled()){ LOG.info("==>>DCHttpRequest.post url[" + no + "]=" + logUrl); } long begin = System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(urlStr); setHttpRequestHead(httpPost); httpPost.setConfig(getCustHttpClientConfig()); if(StringUtils.isNotBlank(json)){ httpPost.setEntity(new StringEntity(json, UTF_8)); } CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); String retString = EntityUtils.toString(entity, UTF_8); EntityUtils.consume(entity); if(LOG.isInfoEnabled()){ LOG.info("==>>DCHttpRequest.post result[" + no + "]=" + retString); } result = retString; } long end = System.currentTimeMillis(); if(LOG.isInfoEnabled()){ LOG.info("==>>DCHttpRequest.post 请求[" + no + "][" + logUrl + "] 耗时:" + ((end-begin)/1000.0) + "秒"); } } finally { httpResponse.close(); } }catch(ConnectTimeoutException e){ LOG.error("==>>DCHttpRequest.post error[" + no + "]:" + e.getMessage()); result = DCDataBean.setConnectTimeoutError(); } catch(SocketTimeoutException e){ LOG.error("==>>DCHttpRequest.post error[" + no + "]:" + e.getMessage()); result = DCDataBean.setSocketTimeoutError(); } catch(ClientProtocolException e){ LOG.error("==>>DCHttpRequest.post error[" + no + "]:" + e.getMessage()); result = DCDataBean.setError(); } catch(ConnectException e){ String msg = e.getMessage(); LOG.error("==>>DCHttpRequest.post error[" + no + "]:" + e.getMessage()); if(msg != null && msg.toUpperCase().equalsIgnoreCase("Connection timed out: connect")){ result = DCDataBean.setConnectTimeoutError(); }else{ result = DCDataBean.setConnectError(); } } catch (Exception e) { LOG.error("==>>DCHttpRequest.post error[" + no + "]:" + e.getMessage()); result = DCDataBean.setError(); } finally { try { httpClient.close(); } catch (IOException e) { } } return result; } }
相关文章推荐
- 用Wireshark简单分析HTTP通信
- 游戏中的网络同步机制——LOCKSTEP
- 推荐大家去博客园看我的博客:http://www.cnblogs.com/bj-xy/点击随笔分类,Python基础学习
- HTTP与HTTPS握手的那些事
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- inotifyz+rsync实现数据网络推送
- Linux 网络配置
- (whh仅供自己参考)进行ip网络请求的步骤
- HTTP中的重定向和请求转发的区别
- Asp.net中的Cache--HttpRuntim.Cache 和 HttpContext.Current.Cache
- HTTP状态码——对照表
- Android中httpURLconnection-post+get
- centos常用网络管理命令
- centos常用网络管理命令
- 一、网络适配-Https
- 网络封包分析工具Charles
- windows和linux下配置tomcat的https通信(ssl单向认证)
- tcp/udp报头
- tcp校验和的实现原理
- 跨域 HTTP 请求