您的位置:首页 > 理论基础 > 计算机网络

HttpRequest请求接口

2016-02-19 12:20 363 查看
Spring mvc 框架请求

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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: