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

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

后端 java eclipse

字节流转字符

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.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;//来源
//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 String mydata=new String();public static void main(String[] args) throws Exception {String mydatav2= new String();// 创建 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);
//                获取数组,把其他的body打印出来,发现是asc码byte[] receivev3 = httpExchange.getRequestBody().readAllBytes();System.out.println(Arrays.toString(receivev3));//                字节流转字符流String utf_8 = new String(receivev3,StandardCharsets.UTF_8);System.out.println(utf_8);//                String have = Arrays.toString(receivev3);
//                System.out.println(have.toString());
//                System.out.println(have);
//                System.out.println(have.length());
//                for(int i=0;i<have.length();i++) {
//                	System.out.println((char)receivev3[i]);
//                }//                char[] message = new char[1000];
//                 String str = new String();
//                 String s=new String();
//                for(int i=0;i<have.length()-2;i++) {
//                	message[i]=(char)receivev3[i];
//                	System.out.println(message[i]);
//                	字符变字符串
//                	s=Character.toString(message[i]);
//                	System.out.println(s);
//                	字符串追加到 str
//                	str=str.concat(s);
//                	System.out.println(str);
//                	System.out.println(str.length());//                }//                mydatav2.copyValueOf(message);
//                
//                System.out.println("revieve"+str);
//                System.out.println(str);
//                System.out.println(have.length());
//                
//                System.out.println("mydatav2"+mydatav2);//                System.out.println(str.length());
//                System.out.println(Arrays.toString(receivev3));//                InputStream have = httpExchange.getRequestBody();
//                byte[] posting = have.readAllBytes();
//                System.out.println(Arrays.toString(posting));// 关闭处理器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/367534.html

相关文章:

  • 【机器学习】消息传递神经网络(MPNN)在分子预测领域的医学应用
  • Python Flask实现蓝图Blueprint配置和模块渲染
  • Vue10-事件修饰符
  • oracle中如何查询特定日期?
  • Python使用rosbag使用getattr只能获取一层的数据,不能直接获取多层数据例如 a.b.c.d。使用for range写一个递归用来获取多层数据
  • LNWT--篇章三小测
  • 【NoSQL】Redis练习
  • Git 和 Github 的使用
  • 学习分享-断路器Hystrix与Sentinel的区别
  • 社区物资交易互助平台的设计
  • 19-Nacos-服务实例的权重设置
  • R语言数据探索和分析23-公共物品问卷分析
  • Webix前端界面框架:深度解析与应用实践
  • Qt基于SQLite数据库的增删查改demo
  • 新书推荐:2.2.4 第11练:消息循环
  • MASA:匹配一切、分割一切、跟踪一切
  • Websocket前端传参:深度解析与实战应用
  • 造假高手——faker
  • 前端工程化工具系列(十二)—— PostCSS(v8.4.38):CSS 转换工具
  • Scanpy(3)单细胞数据分析常规流程
  • 【Stable Diffusion】(基础篇二)—— Stable Diffusion图形界面介绍和基本使用流程
  • OpenCv之简单的人脸识别项目(动态处理页面)
  • 【Linux】进程间通信
  • UI与前端:揭秘两者的微妙差异
  • idea如何根据路径快速在项目中快速打卡该页面
  • 探索成功者的特质——俞敏洪的观点启示
  • MCU的环形FIFO
  • 使用proteus仿真51单片机的流水灯实现
  • 【漏洞复现】Apache OFBiz 路径遍历导致RCE漏洞(CVE-2024-36104)
  • 数据库表中创建字段查询出来却为NULL?