当前位置: 代码迷 >> Ajax >> Ajax 跨域署理
  详细解决方案

Ajax 跨域署理

热度:448   发布时间:2012-09-06 10:37:01.0
Ajax 跨域代理

使用了httpclient做代理请求。

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import jef.database.Condition.Operator;
import jef.database.QB;
import jef.database.query.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.ailk.easyframe.web.common.exception.BusinessException;
import com.ailk.so.redo.MessageCode;
import com.ailk.so.redo.constants.Constants;
import com.ailk.so.redo.persistence.paramconf.entity.SoRedoParam;
import com.ailk.so.redo.service.paramconf.SoRedoParamService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@Transactional
public class AjaxProxyServiceImpl extends AjaxProxyServiceSkeleton implements AjaxProxyService{


	private Log log = LogFactory.getLog(AjaxProxyServiceImpl.class);

	@Autowired
	protected SoRedoParamService paramconf_soRedoParamService;

	public void setParamconf_soRedoParamService(SoRedoParamService obj){
		this.paramconf_soRedoParamService = obj;
	}

	public Map<String, Object> doRequest(Map<String,String> requestParams) {
		Map<String, String> dbParamMap = getDBParamMap(requestParams);
		/** 得到url参数*/
		String requestUrl = dbParamMap.get(requestParams.get(Constants.REQUEST_URL_KEY));
		if(requestUrl == null) {
			BusinessException ex =  new BusinessException(MessageCode.E1013);
			log.error(ex.getFormattedMessage());
			throw ex;
		}
		log.info("requestUrl:" + requestUrl);
		/** 建立一个NameValuePair数组,用于存储欲传送的参数*/
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		HttpClient hc = new DefaultHttpClient();
		/** 给数组加入参数*/
		if(requestParams != null && !requestParams.isEmpty()) {
			Set<Entry<String, String>> pSet = requestParams.entrySet();
			for(Entry<String, String> entry : pSet) {
				String key = entry.getKey();
				String value = entry.getValue();
				if(log.isDebugEnabled()) {
					log.debug("request param " + key + ":" + value);
				}
				if(Constants.REQUEST_URL_KEY.equals(key)) {
					continue;
				}
				//优先查询参数表,如果请求的code在参数表有配置,则用参数表的配置,否则直接使用页面传过来的值
				if(Constants.REQUEST_CODE_KEY.equals(key)) {
					String codeValue = dbParamMap.get(value);
					if(codeValue == null || codeValue.trim().length() == 0) {
						log.info("can not found job code in db by key:" + key);
						codeValue = value;
					}
					qparams.add(new BasicNameValuePair(key, codeValue));
					continue;
				}
				qparams.add(new BasicNameValuePair(key, value));
			}
		}
		
		HttpResponse response;
		try {
			/** 创建url对象并设置编码等属性*/
			URL url = new URL(requestUrl);
			URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(),
					url.getPort(), url.getPath(),
					URLEncodedUtils.format(qparams, "UTF-8"), null);
			/** 创建一个get请求对象*/
			HttpGet httpget = new HttpGet(uri);
			/** 发送get请求,并返回一个HttpResponse对象*/
			response = hc.execute(httpget);
			HttpEntity entity = response.getEntity();
			StringBuffer responseTxtSb = new StringBuffer();
			/** 将返回值得到并放入stringBuffer中*/
			if (entity != null) {
			    InputStream instream = entity.getContent();
			    int len;
			    byte[] tmp = new byte[2048];
			    while ((len = instream.read(tmp)) != -1) {
			    	if(len < 2048) {
			    		byte[] last = new byte[len];
			    		System.arraycopy(tmp, 0, last, 0, len);
			    		responseTxtSb.append(new String(last));
			    	} else {			    	
			    		responseTxtSb.append(new String(tmp));
			    	}
			    }
			    String responseTxt = responseTxtSb.toString();
			    log.info("ajax proxy response:" + responseTxt);
			    /** 解析返回值字符串*/
			    if(responseTxt.length()  != 0) {
			    	Type type = new TypeToken<ProxyResponse>() {}.getType();
			    	ProxyResponse result =  new Gson().fromJson(responseTxt, type);
			    	String urlKey = requestParams.get(Constants.REQUEST_URL_KEY);
			    	if(!urlKey.equals("check_status_url")) {
			    		if(!result.getSuccess()) {
			    			throw new BusinessException(-1, result.getMessage());
			    		}
			    	} else {
			    		if(!result.getSuccess()) {
			    			log.error("check job status error.");
			    			return null;
			    		}
			    	}
			    	Object data = result.getData();
			    	Integer tatal = result.getTotal();
			    	
			    	Map<String, Object> resultMap = new HashMap<String, Object>();
			    	if(data  != null) {
			    		resultMap.put("data",  data);
			    	}
			    	if(tatal != null) {
			    		resultMap.put("tatal",  tatal);
			    	}
			    	
			    	if(!resultMap.isEmpty()) {
			    		return resultMap;
			    	}
			    	return null;
			    }
			}
		} catch (ClientProtocolException ce) {
			log.error(ce.getMessage());
			ce.printStackTrace();
			throw new BusinessException(-1, ce.getMessage());
		} catch (IOException ie) {
			log.error(ie.getMessage());
			ie.printStackTrace();
			throw new BusinessException(-1, ie.getMessage());
		} catch (URISyntaxException ue) {
			log.error(ue.getMessage());
			ue.printStackTrace();
			throw new BusinessException(-1, ue.getMessage());
		}
		return null;
	}

	private Map<String, String> getDBParamMap(Map<String,String> requestParams) {
		String urlKey = requestParams.get(Constants.REQUEST_URL_KEY);
		String code = requestParams.get(Constants.REQUEST_CODE_KEY);
		if(urlKey == null || urlKey.trim().length() == 0) {
			throw new BusinessException(MessageCode.E1012);
		}
		
		List<SoRedoParam> paramList = getParamList(Constants.AJAX_PROXY_PARAM_TYPE, urlKey,code);
		Map<String, String> paramMap = new HashMap<String, String>();
		for(SoRedoParam param : paramList) {
			log.info("ajax request info:" + param.getParamName() + "=" + param.getParamValue());
			paramMap.put(param.getParamName(), param.getParamValue());
		}
		return paramMap;
	}

	private List<SoRedoParam> getParamList(String paramType, String... paramNames) {
		Query<SoRedoParam> paramQuery = QB.create(SoRedoParam.class);
		paramQuery.addCondition(SoRedoParam.Field.paramType, paramType);
		if(paramNames == null) {
			log.error("param name is null");
			return null;
		}
		paramQuery.addCondition(SoRedoParam.Field.paramName, Operator.IN, paramNames);
		List<SoRedoParam> paramList = paramconf_soRedoParamService.find(paramQuery.getInstance());
		
		if(paramList == null || paramList.size() == 0) {
			String errMsg = "not found param value by param name:" +paramNames;
			log.error(errMsg);
			throw new BusinessException(MessageCode.E1000, errMsg);
		}
		return paramList;
	}


	class ProxyResponse {
		/**成功标记*/
		private Boolean success;	
		/**错误对象 */
		private String message;
		/**待传输数据*/
		private Object data;
		/**数据总数 当返回结果为数组时*/
		private Integer total;
		
		public Boolean getSuccess() {
			return success;
		}
		public void setSuccess(Boolean success) {
			this.success = success;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public Object getData() {
			return data;
		}
		public void setData(Object data) {
			this.data = data;
		}
		public Integer getTotal() {
			return total;
		}
		public void setTotal(Integer total) {
			this.total = total;
		}
	};


}
  相关解决方案