当前位置: 首页 > news >正文

java 原生http服务器 测试JS前端ajax访问实现跨域

后端

package Httpv3;import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;//来源
//https://blog.csdn.net/xietansheng/article/details/78704783//浏览器访问: http://localhost:8080/、http://localhost:8080/bb,输出: Hello World//浏览器访问: http://localhost:8080/aa、http://localhost:8080/aa/bb,输出: Hello World AA
//                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
//原文链接:https://blog.csdn.net/xietansheng/article/details/78704783public class Mainv2 {public static void main(String[] args) throws Exception {// 创建 http 服务器, 绑定本地 8080 端口HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);// 创上下文监听, "/" 表示匹配所有 URI 请求httpServer.createContext("/", new HttpHandler() {@Overridepublic void handle(HttpExchange httpExchange) throws IOException {System.out.println("addr: " + httpExchange.getRemoteAddress() +     // 客户端IP地址"; protocol: " + httpExchange.getProtocol() +               // 请求协议: HTTP/1.1"; method: " + httpExchange.getRequestMethod() +            // 请求方法: GET, POST 等"; URI: " + httpExchange.getRequestURI());                  // 请求 URI// 获取请求头String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");System.out.println("User-Agent: " + userAgent);// 响应内容
//                byte[] respContents = "Hello World".getBytes("UTF-8");byte[] respContents = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+ "<note>\r\n"+ "  <to>Tove</to>\r\n"+ "  <from>Jani</from>\r\n"+ "  <heading>Reminder</heading>\r\n"+ "  <body>Don't forget me this weekend!</body>\r\n"+ "</note>").getBytes("UTF-8");// 设置响应头//                httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
//               参数解释-允许跨域的各个参数
//              https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Request-HeadershttpExchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers","*");httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods","*");
//              允许接收各种消息头 对应前端 xhr.setRequestHeader('Content-Type', 'application/json');httpExchange.getResponseHeaders().add("Access-Control-Request-Headers","*");httpExchange.getResponseHeaders().add("Access-Control-Expose-Headers","*" );
//              对应前端特定消息头 xhr.setRequestHeader('Content-Type', 'application/json');httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");// 设置响应code和内容长度httpExchange.sendResponseHeaders(200, respContents.length);// 设置响应内容httpExchange.getResponseBody().write(respContents);//                测试数据String receive = httpExchange.getResponseBody().toString();System.out.println(receive);String receivev2 = httpExchange.getRequestBody().toString();System.out.println(receivev2);// 关闭处理器httpExchange.close();//              来源
//              https://vimsky.com/examples/detail/java-method-com.sun.net.httpserver.HttpExchange.getResponseHeaders.html//                Headers responseHeaders = httpExchange.getResponseHeaders();
//        	    responseHeaders.add("Access-Control-Allow-Origin", "*");
//        	    responseHeaders.add("Access-Control-Allow-Headers", "*");
//        	    X-Custom-Header
//              httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
//        	    httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods","*");
//        	    httpExchange.sendResponseHeaders(200, respContents.length);
//        	    OutputStream outputStream = httpExchange.getResponseBody();
//        	    outputStream.write(httpExchange.getResponseCode());
//        	    outputStream.close();//        	    byte[] respContentsv3 = "Hello World".getBytes("UTF-8");
//        	    httpExchange.sendResponseHeaders(200, respContentsv3.length);
//        	    httpExchange.getResponseBody().write(respContentsv3);//        	    System.out.println("message"+httpExchange.getRequestBody().toString());//        	    httpExchange.close();}});// 创建上下文监听, 处理 URI 以 "/aa" 开头的请求httpServer.createContext("/aa", new HttpHandler() {@Overridepublic void handle(HttpExchange httpExchange) throws IOException {byte[] respContents = "Hello World AA".getBytes("UTF-8");httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");httpExchange.sendResponseHeaders(200, respContents.length);httpExchange.getResponseBody().write(respContents);httpExchange.close();
//                来源
//                https://vimsky.com/examples/detail/java-method-com.sun.net.httpserver.HttpExchange.getResponseHeaders.html// Add the header to avoid error:// “No 'Access-Control-Allow-Origin' header is present on the requested resource”
//                
//                Headers responseHeaders = httpExchange.getResponseHeaders();
//        	    responseHeaders.add("Access-Control-Allow-Origin", "*");
//        	    httpExchange.sendResponseHeaders(200, respContents.length);
//
//        	    OutputStream outputStream = httpExchange.getResponseBody();
//        	    outputStream.write(httpExchange.getResponseCode());
//        	    outputStream.close();
//        	    }});// 启动服务httpServer.start();}}

前端

<!DOCTYPE html><!-- 来源 -->
<!-- https://cloud.tencent.com/developer/article/1705089 -->
<!-- https://geek-docs.com/ajax/ajax-questions/19_ajax_javascript_send_json_object_with_ajax.html -->
<!-- 配合java后端可以监听 -->
<!-- //原文链接:https://blog.csdn.net/xietansheng/article/details/78704783 --><html lang="en"><head><meta charset="UTF-8"><title>Title</title><script>function fun() {//发送异步请求//1、创建核心对象// var xmlhttp;// if (window.XMLHttpRequest) { //code for IE7+,Firefox,chrome,opera,safari// 	xmlhttp = new XMLHttpRequest();// } else { //code for IE6,IE5// 	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");// }// //2、建立连接// /*//  * 参数:请求方式、请求的url路径、同步或异步请求(true为异步)//  * get方式:请求参数在url后面拼接,send方法为空;//  * post方式:请求参数在send方法中定义。//  * */// xmlhttp.open("GET", "ajaxServlet?username=Tim", true);// //3、发送请求// xmlhttp.send();// //4、接收及处理响应结果,当服务器响应成功了再获取// xmlhttp.onreadystatechange = function() { //当xmlhttp对象就绪状态改变时会触发事件// 	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //请求已完成且响应就绪,响应状态码为200// 		alert(xmlhttp.responseText);// 	}// };// https://geek-docs.com/ajax/ajax-questions/19_ajax_javascript_send_json_object_with_ajax.html// 创建XMLHttpRequest对象var xhr = new XMLHttpRequest();// 设置请求类型和URL// xhr.open('POST', 'http://example.com/api', true);// xhr.open('POST', 'http://localhost:8080/aa', true);// xhr.open('POST', '/aa', true);// xhr.open('POST', 'http://localhost:8080/aa', true);xhr.open('POST', 'http://localhost:8080', true);// 设置请求头xhr.setRequestHeader('Content-Type', 'application/json');// xhr.setRequestHeader('X-Custom-Header', 'value');// xhr.setRequestHeader('Access-Control-Allow-Origin','*');console.log("请求头已设置\n");// 监听服务器响应// xhr.onreadystatechange = function() {//   if (xhr.readyState === 4 && xhr.status === 200) {//     // 从服务器获取响应//     var response = JSON.parse(xhr.responseText);//     console.log(response);// 	console.log(getAllResponseHeaders());//   }// };// 构建JSON对象var data = {name: 'John',age: 25,email: 'john@example.com'};// 将JSON对象转换为字符串var jsonData = JSON.stringify(data);// 发送数据xhr.send(jsonData);// 注释掉就会爆 POST 错误提示//4、接收及处理响应结果,当服务器响应成功了再获取xhr.onreadystatechange = function() { //当xmlhttp对象就绪状态改变时会触发事件if (xhr.readyState == 4 && xhr.status == 200) { //请求已完成且响应就绪,响应状态码为200alert(xhr.responseText);console.log("检测的正确的返回\n");}else{console.log("检测到错误的返回\n");}console.log("检测到返回函数\n");};}</script></head><body><input type="button" value="发送异步请求" onclick="fun();"><input type="text"></body>
</html>

http://www.lryc.cn/news/362484.html

相关文章:

  • 捋一捋C++中的逻辑运算(一)——表达式逻辑运算
  • qcom 平台系统签名流程
  • 从零开始实现自己的串口调试助手(5) -实现HEX显示/发送/接收
  • 【计算机毕设】基于SpringBoot的民宿在线预定平台设计与实现 - 源码免费(私信领取)
  • 大数据—数据分析概论
  • centos7下卸载MySQL,Oracle数据库
  • Spring解决循环依赖
  • RUST运算符重载
  • 描述一下 Array.forEach() 循环和 Array.map() 方法之间的主要区别
  • 在GEE中显示矢量或栅格数据的边界(包含样式设计)
  • django使用fetch上传文件
  • linux安装docker步骤
  • Unity DOTS技术(一)简介
  • 深度解读ChatGPT基本原理
  • python实现——分类类型数据挖掘任务(图形识别分类任务)
  • 【安卓跨进程通信IPC】-- Binder
  • 大数据之Schedule调度错误(一)
  • DiffIR论文阅读笔记
  • prometheus+alertmanager+webhook钉钉机器人告警
  • ctfshow 年CTF web
  • 原型链、闭包、手写一个闭包函数、 闭包有哪些优缺点、原型链继承
  • linux中SSH_ASKPASS全局变量的作用
  • 9 -力扣高频 SQL 50 题(基础版)
  • TCP的重传机制
  • pg 数据库,获取时间字段值的具体小时,赋值给其他字段
  • 做视频号小店什么类目最容易爆单?其实,弄懂这三点就会选品了
  • Nginx作为下载站点
  • vue3简单快速实现主题切换功能
  • 国联易安:网络反不正当竞争,要防患于未然
  • Linux 网络配置 01