Http 远程调用

Http 远程调用


1.HttpResquestProxy.java类。

package com.cassandra.http.common;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cassandra.http.bean.Response;

public class HttpRequestProxy
{
  private Log logger = LogFactory.getLog(HttpRequestProxy.class);
  
  private String connectionUrl;
  private Map<String,String>  paramMap = new HashMap<String,String>();
  private Map<String, String> headMap = new HashMap<String,String>();
  private HttpClient httpClient;
  
  
  public HttpRequestProxy()
  {
	  httpClient = new HttpClient();
	  httpClient.getParams().setContentCharset("utf-8");
  }
      
  public HttpRequestProxy(String connectionUrl) {
	httpClient = new HttpClient();  
    setConnectionUrl(connectionUrl);
  }
  
  public void clearHttpRequest(){
	  paramMap.clear();
	  headMap.clear();
  }
  public void appendParam(String key, String value) {
	  try {
		  if (StringUtils.isEmpty(value)) {
			  return;
		  }
	      paramMap.put(key, URLEncoder.encode(value, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  }

  public void appendParam(Map<String, String> params) {
    if ((params == null) || (params.isEmpty())) {
      return;
    }   
    for (Map.Entry entry : params.entrySet()) {
      paramMap.put((String)entry.getKey(),(String)entry.getValue());
    }
  }

  public void setHead(Map<String, String> params) {
    this.headMap.putAll(params);
  }

  private String getConnectionUrl() {
    return this.connectionUrl;
  }

  public void setConnectionUrl(String connectionUrl) {
    this.connectionUrl = connectionUrl;
  }

  public String sendRequest()
  {
    if (StringUtils.isBlank(getConnectionUrl())) {
    	Response res = new Response();
    	res.setStatus(-1);
    	res.setMessage("用户中心地址异常!");
	    return JSONObject.fromObject(res).toString();
     }
    logger.debug("sendRequest start!");
     try {
    	 PostMethod postMethod = new PostMethod(getConnectionUrl());  
      
     if (!(this.headMap.isEmpty())) {
    	for (Map.Entry head : this.headMap.entrySet()) {
          postMethod.addRequestHeader((String)head.getKey(), (String)head.getValue());  
        }
     }
     
     if (!(this.paramMap.isEmpty())) {
     	for (Map.Entry head : this.paramMap.entrySet()) {
           postMethod.addParameter((String)head.getKey(), (String)head.getValue());  
         }
      }      
      httpClient.executeMethod(postMethod);
      
      int code = postMethod.getStatusCode();
      if (code != 200) {
    	logger.debug("$$$$$$$$$$$$$$ code" + code);
        throw new Exception();
      }
      logger.debug("$$$$$$$$$$$$$$ code" + code);
      String result =  postMethod.getResponseBodyAsString();
      postMethod = null;
     /* InputStream in = postMethod.getResponseBodyAsStream();
      BufferedReader breader = new BufferedReader(
        new InputStreamReader(in, "gbk"));
      StringBuffer strResult = new StringBuffer();
      String strLine = breader.readLine();
      while(strLine != null){
    	  strResult.append(strLine);
    	  strResult.append("\n");
    	  strLine = breader.readLine();
      }
      */
      logger.debug("sendRequest end!");
      logger.info("请求结束,返回result= "+result);
      return result;
    } catch (Exception e) {
    	logger.debug("$$$$$$$$$$$$$$$$$$$ e" + e.getMessage());
    	Response res = new Response();
    	res.setStatus(-1);
    	res.setMessage("网络异常!");
	    return JSONObject.fromObject(res).toString();
    } finally {
      
    }
  }
}


2.方法调用示例

	public JSONObject remarkEdit(String memberId, String comment, String token){
		logger.info("HttpRequestUtils.remarkEdit() start");
		long startTime = System.currentTimeMillis();
		JSONObject jsonResult = new JSONObject();
		HttpRequestProxy httpProxy = new HttpRequestProxy(ENT_ACCOUNT_CENTER_URL);
		JSONObject json = new JSONObject();
		json.put("memberId", memberId);
		json.put("comment", comment);
		httpProxy.appendParam(SERVICE_KEY,UPDATE_ENTERPRISE_MEMBER);
		httpProxy.appendParam(PARAMS_KEY,JSONConverter.convertToString(json));
		httpProxy.appendParam(TOKEN, token);
		
		String result = httpProxy.sendRequest();
		jsonResult = JSONObject.fromObject(result);
		
		long costTime = System.currentTimeMillis() - startTime;
		logger.info("HttpRequestUtils.remarkEdit() cost time:"+ costTime);
		logger.info("HttpRequestUtils.remarkEdit() end");
		return jsonResult;
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值