ajax 跨域请求api_java跨域请求的三种方法

2022-09-23 11:27:35 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。


目录:

(1)ajax跨域解决方案之代理机制实现原理

(2)ajax跨域解决方案之代理机制的代码实现


(1)ajax跨域解决方案之代理机制实现原理

让ajax请求访问servlet,可以让ajax请求跨域,通过直接本应用中的资源servlet,ajax可以不跨域访问本应用中的servlet,让java程序发送Get,Post请求,来访问2号服务器中的的servlet

用java代码模拟浏览器的行为,就好比在浏览器地址栏输入地址敲回车一样

首先把架包导入:创建lib目录,复制进去 选中右键Add as library

HttpClientSendGet:

代码语言:javascript复制
package com.bjpowernode.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpClientSendGet {
    public static void main(String[] args) throws Exception {
        // 使用java代码去发送HTTP get请求
        // 目标地址
        //String url = "https://www.baidu.com";
        String url = "http://localhost:8081/b/hello";
        HttpGet httpGet = new HttpGet(url);

        // 设置类型 "application/x-www-form-urlencoded" "application/json"
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        //System.out.println("调用URL: "   httpGet.getURI());

        // httpClient实例化
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求并获取返回
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        //System.out.println("返回状态码:"   response.getStatusLine());

        // 显示结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        StringBuffer responseSB = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            responseSB.append(line);
        }
        System.out.println("服务器响应的数据:"   responseSB);
        reader.close();

        httpClient.close();
    }
}

运行:

(2)ajax跨域解决方案之代理机制的代码实现

b站点创建Servlet:

TargetServlet:

代码语言:javascript复制
package com.bjpowernode.b.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/target")
public class TargetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 响应一个json字符串。
        response.getWriter().print("{"username":"jackson"}");
    }
}

a站点需要servlet,首先需要加入servlet依赖:

引入架包:httpclient架包

ProxyServlet:发送get请求,访问b站点TargerServlet,请求响应回来数据在进行响应

代码语言:javascript复制
package com.bjpowernode.javaweb.servlet;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@WebServlet("/proxy")
public class ProxyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 通过httpclient组件,发送HTTP GET请求,访问 TargetServlet
        HttpGet httpGet = new HttpGet("http://localhost:8081/b/target");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse resp = httpClient.execute(httpGet);
        HttpEntity entity = resp.getEntity();
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        StringBuffer responseSB = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            responseSB.append(line);
        }
        reader.close();
        httpClient.close();
        // b站点响应回来的数据
        response.getWriter().print(responseSB);
    }
}

ajax5.html:发送ajax请求:

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用代理机制完成ajax跨域访问</title>
</head>
<body>
<script type="text/javascript">
    // ES6当中的有一个新语法:箭头函数。
    window.onload = () => {
        document.getElementById("btn").onclick = () => {
            // 发送ajax请求
            // 1.创建核心对象
            const xmlHttpRequest = new XMLHttpRequest(); // const可以声明变量。(可以自己研究一下:var let const声明变量时有什么区别)
            // 2.注册回调函数
            xmlHttpRequest.onreadystatechange = () => {
                if (xmlHttpRequest.readyState == 4) {
                    // 这里也可以使用区间的方式,因为状态码是200~299都是正常响应结束。
                    if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
                        document.getElementById("mydiv").innerHTML = xmlHttpRequest.responseText
                    }
                }
            }
            // 3.开启通道
            xmlHttpRequest.open("GET", "/a/proxy", true)
            // 4.发送请求
            xmlHttpRequest.send()
        }
    }
</script>
<button id="btn">使用代理机制解决ajax跨域访问</button>
<div id="mydiv"></div>
</body>
</html>

点击按钮:

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172579.html原文链接:https://javaforall.cn

0 人点赞