通过httpClinet解决跨域问题

项目中碰到一个问题,在跨域时请求时,IE6和IE8都可以,但IE7时,出现问题,经过多次尝试无效后,通HTTPCLient转发和响应,解决问题,HttpClinet支持多线程时需要另外处理,可以仔细看一下API,下面提源代码
    public void doUrlForward(@Param(name = "urlRequest") String urlRequest,
                             HttpServletRequest request, HttpServletResponse response) {
        HttpClient httpClient = new HttpClient();
        PostMethod method = null;
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        try {
            String url = URLDecoder.decode(urlRequest, "UTF-8");
            method = new PostMethod(url);
            // request.setCharacterEncoding("UTF-8");
            Map<String, String[]> paramsMap = (Map<String, String[]>) request.getParameterMap();
            Set<Entry<String, String[]>> set = paramsMap.entrySet();
            Iterator<Entry<String, String[]>> it = set.iterator();
            while (it.hasNext()) {
                Entry<String, String[]> entry = it.next();
                String key = entry.getKey();
                if ("action".equalsIgnoreCase(key) || key.startsWith("event_")
                        || "urlRequest".equalsIgnoreCase(key) || "urlRequest".equalsIgnoreCase(key)) {
                    continue;
                }
                // String value = request.getParameter(key);
                String value = "";
                if (null != entry.getValue() && entry.getValue().length > 0) {
                    value = entry.getValue()[0];
                }
                NameValuePair param = new NameValuePair(key, value);
                paramList.add(param);
            }
            NameValuePair[] params = new NameValuePair[paramList.size()];
            params = paramList.toArray(params);
            method.setRequestBody(params);
            int status = httpClient.executeMethod(method);
            String result = null;
            if (HttpStatus.SC_OK == status) {
                InputStream in = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                result = br.readLine();
                br.close();
                in.close();
            }
            ResponseWriteUtils.writeJson(response, result);
        } catch (Exception e) {
            logger.error(e.toString());
            ResponseWriteUtils.writeJson(response, DataUtils.exceptionToJson(e.toString(), null));
        } finally {
            if (null != method) {
                method.releaseConnection();
            }
        }
    }
}

你可能感兴趣的:(通过httpClinet解决跨域问题)