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

就项目跨域问题的前后台解决办法,采用JSONP和HttpClient技术

2018-03-14 10:49 543 查看
最近做项目的时候遇到了一些跨域问题,虽然网上对于跨域的问题分享还挺多的。不过当我实际遇到的时候还是有点懵。趁手头工作不多,写篇文章总结下。

什么是跨域

跨域是指从一个域名的网页去请求另一个域名的资源。比如从www.baidu.com 页面去请求 www.google.com 的资源。跨域的严格一点的定义是:只要 协议,域名,端口有任何一个的不同,就被当作是跨域
举一个简单的例子,项目A向项目调用项目B的请求,就涉及到跨域问题,这里分浏览器调用,和服务器调用,
浏览器调用:这里我们用http://localhost:8091/InProject/listUI.do,这个页面里采用ajax方式调用http://localhost:8090/InPro/test/testJsonp.do



访问



浏览器报错:No 'Access-Control-Allow-Origin’


此时我们可以采用jsonp技术解决这样的问题





再次访问:





这样浏览器跨域问题就解决了,但是这种方式并不安全,现在大多数企业采用服务器跨域访问技术,及HttpClient,下面我也介绍下该测试方法:
HttpClinet依赖的jar包:
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.4</version>

</dependency>
ssm的配置文件,以及工具类,https://download.csdn.net/download/zhaogangyyxf/10285655



定义HttpClient工具类,包含get请求,post请求等:
@Service
public class JsonClientUtil {
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig requestConfig;
    
    /**
     * 执行get请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url,Map<String, String> params,String encode) throws Exception {
        if(null != params){
            URIBuilder builder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.setParameter(entry.getKey(), entry.getValue());
            }
            url = builder.build().toString();
        }
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                if(encode == null){
                    encode = "UTF-8";
                }
                return EntityUtils.toString(response.getEntity(), encode);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            // 此处不能关闭httpClient,如果关闭httpClient,连接池也会销毁
        }
        return null;
    }
    
    public String doGet(String url, String encode) throws Exception{
        return this.doGet(url, null, encode);
    }
    
    public String doGet(String url) throws Exception{
        return this.doGet(url, null, null);
    }

    /**
     * 带参数的get请求
     * 
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, String> params) throws Exception {
        return this.doGet(url, params, null);
    }

    /**
     * 执行POST请求
     * 
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public String doPost(String url, Map<String, String> params,String encode) throws Exception {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (null != params) {
            // 设置2个post参数,一个是scope、一个是q
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = null;
            if(encode!=null){
                formEntity = new UrlEncodedFormEntity(parameters,encode);
            }else{
                formEntity = new UrlEncodedFormEntity(parameters);
            }
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }

}
测试类:采用8090访问8091的方式



8091下的代码:



测试结果为:



以上代码仅是我测试代码,如有问题联系我的博客。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: