ToB企服应用市场:ToB评测及商务社交产业平台

标题: java 原生http服务器 测试JS前端ajax访问实现跨域传post数据 [打印本页]

作者: 圆咕噜咕噜    时间: 2024-6-19 20:59
标题: java 原生http服务器 测试JS前端ajax访问实现跨域传post数据


后端 java eclipse
字节流转字符
  1. package Httpv3;
  2. import com.sun.net.httpserver.Headers;
  3. import com.sun.net.httpserver.HttpExchange;
  4. import com.sun.net.httpserver.HttpHandler;
  5. import com.sun.net.httpserver.HttpServer;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.InetSocketAddress;
  10. import java.nio.charset.StandardCharsets;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. //来源
  14. //https://blog.csdn.net/xietansheng/article/details/78704783
  15. //浏览器访问: http://localhost:8080/、http://localhost:8080/bb,输出: Hello World
  16. //浏览器访问: http://localhost:8080/aa、http://localhost:8080/aa/bb,输出: Hello World AA
  17. //                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  18. //原文链接:https://blog.csdn.net/xietansheng/article/details/78704783
  19. public class Mainv2 {
  20.         public String mydata=new String();
  21.     public static void main(String[] args) throws Exception {
  22.            
  23.             String mydatav2= new String();
  24.         // 创建 http 服务器, 绑定本地 8080 端口
  25.         HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
  26.         // 创上下文监听, "/" 表示匹配所有 URI 请求
  27.         
  28.         httpServer.createContext("/", new HttpHandler() {
  29.             @Override
  30.             public void handle(HttpExchange httpExchange) throws IOException {
  31.                 System.out.println("addr: " + httpExchange.getRemoteAddress() +     // 客户端IP地址
  32.                         "; protocol: " + httpExchange.getProtocol() +               // 请求协议: HTTP/1.1
  33.                         "; method: " + httpExchange.getRequestMethod() +            // 请求方法: GET, POST 等
  34.                         "; URI: " + httpExchange.getRequestURI());                  // 请求 URI
  35.                 // 获取请求头
  36.                 String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");
  37.                 System.out.println("User-Agent: " + userAgent);
  38.                
  39.                 // 响应内容
  40. //                byte[] respContents = "Hello World".getBytes("UTF-8");
  41.                 byte[] respContents = ("<?xml version="1.0" encoding="UTF-8"?>\r\n"
  42.                                 + "<note>\r\n"
  43.                                 + "  <to>Tove</to>\r\n"
  44.                                 + "  <from>Jani</from>\r\n"
  45.                                 + "  <heading>Reminder</heading>\r\n"
  46.                                 + "  <body>Don't forget me this weekend!</body>\r\n"
  47.                                 + "</note>").getBytes("UTF-8");
  48.                 // 设置响应头
  49.                
  50. //                httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
  51. //               参数解释-允许跨域的各个参数
  52. //              https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Request-Headers
  53.               httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");
  54.               httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers","*");
  55.               httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods","*");
  56. //              允许接收各种消息头 对应前端 xhr.setRequestHeader('Content-Type', 'application/json');
  57.               httpExchange.getResponseHeaders().add("Access-Control-Request-Headers","*");
  58.               httpExchange.getResponseHeaders().add("Access-Control-Expose-Headers","*" );
  59. //              对应前端特定消息头 xhr.setRequestHeader('Content-Type', 'application/json');
  60.               httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
  61.                
  62.               
  63.               // 设置响应code和内容长度
  64.                 httpExchange.sendResponseHeaders(200, respContents.length);
  65.                 // 设置响应内容
  66.                 httpExchange.getResponseBody().write(respContents);
  67.                
  68. //                测试数据
  69. //                String receive = httpExchange.getResponseBody().toString();
  70. //                System.out.println(receive);
  71. //               
  72. //                String receivev2 = httpExchange.getRequestBody().toString();
  73. //                System.out.println(receivev2);
  74. //                获取数组,把其他的body打印出来,发现是asc码
  75.                 byte[] receivev3 = httpExchange.getRequestBody().readAllBytes();
  76.                 System.out.println(Arrays.toString(receivev3));
  77.                
  78. //                字节流转字符流
  79.                 String utf_8 = new String(receivev3,StandardCharsets.UTF_8);
  80.                 System.out.println(utf_8);
  81.                
  82.                
  83.                
  84.                
  85. //                String have = Arrays.toString(receivev3);
  86. //                System.out.println(have.toString());
  87. //                System.out.println(have);
  88. //                System.out.println(have.length());
  89. //                for(int i=0;i<have.length();i++) {
  90. //                        System.out.println((char)receivev3[i]);
  91. //                }
  92.                
  93. //                char[] message = new char[1000];
  94. //                 String str = new String();
  95. //                 String s=new String();
  96. //                for(int i=0;i<have.length()-2;i++) {
  97. //                        message[i]=(char)receivev3[i];
  98. //                        System.out.println(message[i]);
  99. //                        字符变字符串
  100. //                        s=Character.toString(message[i]);
  101. //                        System.out.println(s);
  102. //                        字符串追加到 str
  103. //                        str=str.concat(s);
  104. //                        System.out.println(str);
  105. //                        System.out.println(str.length());
  106.                        
  107. //                }
  108.                
  109.                
  110.                
  111.                
  112. //                mydatav2.copyValueOf(message);
  113. //               
  114. //                System.out.println("revieve"+str);
  115. //                System.out.println(str);
  116. //                System.out.println(have.length());
  117. //               
  118. //                System.out.println("mydatav2"+mydatav2);
  119.                
  120.                
  121.                
  122.                
  123. //                System.out.println(str.length());
  124. //                System.out.println(Arrays.toString(receivev3));
  125.                
  126.                
  127. //                InputStream have = httpExchange.getRequestBody();
  128. //                byte[] posting = have.readAllBytes();
  129. //                System.out.println(Arrays.toString(posting));
  130.                
  131.                 // 关闭处理器
  132.                 httpExchange.close();
  133.                
  134. //              来源
  135. //              https://vimsky.com/examples/detail/java-method-com.sun.net.httpserver.HttpExchange.getResponseHeaders.html
  136.                
  137. //                Headers responseHeaders = httpExchange.getResponseHeaders();
  138. //                    responseHeaders.add("Access-Control-Allow-Origin", "*");
  139. //                    responseHeaders.add("Access-Control-Allow-Headers", "*");
  140. //                    X-Custom-Header
  141. //              httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
  142. //                    httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods","*");
  143. //                    httpExchange.sendResponseHeaders(200, respContents.length);
  144. //                    OutputStream outputStream = httpExchange.getResponseBody();
  145. //                    outputStream.write(httpExchange.getResponseCode());
  146. //                    outputStream.close();
  147.                
  148. //                    byte[] respContentsv3 = "Hello World".getBytes("UTF-8");
  149. //                    httpExchange.sendResponseHeaders(200, respContentsv3.length);
  150. //                    httpExchange.getResponseBody().write(respContentsv3);
  151.                     
  152. //                    System.out.println("message"+httpExchange.getRequestBody().toString());
  153.                     
  154. //                    httpExchange.close();
  155.                
  156.             }
  157.             
  158.             
  159.             
  160.         });
  161.         // 创建上下文监听, 处理 URI 以 "/aa" 开头的请求
  162.         httpServer.createContext("/aa", new HttpHandler() {
  163.             @Override
  164.             public void handle(HttpExchange httpExchange) throws IOException {
  165.                 byte[] respContents = "Hello World AA".getBytes("UTF-8");
  166.                
  167.                 httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
  168.                 httpExchange.sendResponseHeaders(200, respContents.length);
  169.                 httpExchange.getResponseBody().write(respContents);
  170.                 httpExchange.close();
  171. //                来源
  172. //                https://vimsky.com/examples/detail/java-method-com.sun.net.httpserver.HttpExchange.getResponseHeaders.html
  173.                 // Add the header to avoid error:
  174.                     // “No 'Access-Control-Allow-Origin' header is present on the requested resource”
  175. //               
  176. //                Headers responseHeaders = httpExchange.getResponseHeaders();
  177. //                    responseHeaders.add("Access-Control-Allow-Origin", "*");
  178. //                    httpExchange.sendResponseHeaders(200, respContents.length);
  179. //
  180. //                    OutputStream outputStream = httpExchange.getResponseBody();
  181. //                    outputStream.write(httpExchange.getResponseCode());
  182. //                    outputStream.close();
  183. //                    
  184.                     
  185.                     
  186.             }
  187.             
  188.         });
  189.         // 启动服务
  190.         httpServer.start();
  191.     }
  192. }
复制代码

前端
  1. <!DOCTYPE html>
  2. <!-- 来源 -->
  3. <!-- https://cloud.tencent.com/developer/article/1705089 -->
  4. <!-- https://geek-docs.com/ajax/ajax-questions/19_ajax_javascript_send_json_object_with_ajax.html -->
  5. <!-- 配合java后端可以监听 -->
  6. <!-- //原文链接:https://blog.csdn.net/xietansheng/article/details/78704783 -->
  7. <html lang="en">
  8.         <head>
  9.                 <meta charset="UTF-8">
  10.                 <title>Title</title>
  11.                 <script>
  12.                         function fun() {
  13.                                 //发送异步请求
  14.                                 //1、创建核心对象
  15.                                 // var xmlhttp;
  16.                                 // if (window.XMLHttpRequest) { //code for IE7+,Firefox,chrome,opera,safari
  17.                                 //         xmlhttp = new XMLHttpRequest();
  18.                                 // } else { //code for IE6,IE5
  19.                                 //         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  20.                                 // }
  21.                                 // //2、建立连接
  22.                                 // /*
  23.                                 //  * 参数:请求方式、请求的url路径、同步或异步请求(true为异步)
  24.                                 //  * get方式:请求参数在url后面拼接,send方法为空;
  25.                                 //  * post方式:请求参数在send方法中定义。
  26.                                 //  * */
  27.                                 // xmlhttp.open("GET", "ajaxServlet?username=Tim", true);
  28.                                
  29.                                 // //3、发送请求
  30.                                 // xmlhttp.send();
  31.                                 // //4、接收及处理响应结果,当服务器响应成功了再获取
  32.                                 // xmlhttp.onreadystatechange = function() { //当xmlhttp对象就绪状态改变时会触发事件
  33.                                 //         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //请求已完成且响应就绪,响应状态码为200
  34.                                 //                 alert(xmlhttp.responseText);
  35.                                 //         }
  36.                                 // };
  37.                                
  38.                                 // https://geek-docs.com/ajax/ajax-questions/19_ajax_javascript_send_json_object_with_ajax.html
  39.                                
  40.                                
  41.                                 // 创建XMLHttpRequest对象
  42.                                 var xhr = new XMLHttpRequest();
  43.                                
  44.                                 // 设置请求类型和URL
  45.                                 // xhr.open('POST', 'http://example.com/api', true);
  46.                                 // xhr.open('POST', 'http://localhost:8080/aa', true);
  47.                                 // xhr.open('POST', '/aa', true);
  48.                                 // xhr.open('POST', 'http://localhost:8080/aa', true);
  49.                                 xhr.open('POST', 'http://localhost:8080', true);
  50.                                 // 设置请求头
  51.                                 xhr.setRequestHeader('Content-Type', 'application/json');
  52.                                
  53.                                 // xhr.setRequestHeader('X-Custom-Header', 'value');
  54.                                 // xhr.setRequestHeader('Access-Control-Allow-Origin','*');
  55.                                 console.log("请求头已设置\n");
  56.                                 // 监听服务器响应
  57.                                 // xhr.onreadystatechange = function() {
  58.                                 //   if (xhr.readyState === 4 && xhr.status === 200) {
  59.                                 //     // 从服务器获取响应
  60.                                 //     var response = JSON.parse(xhr.responseText);
  61.                                 //     console.log(response);
  62.                                 //         console.log(getAllResponseHeaders());
  63.                                 //   }
  64.                                 // };
  65.                                
  66.                                 // 构建JSON对象
  67.                                 var data = {
  68.                                   name: 'John',
  69.                                   age: 25,
  70.                                   email: 'john@example.com'
  71.                                 };
  72.                                
  73.                                 // 将JSON对象转换为字符串
  74.                                 var jsonData = JSON.stringify(data);
  75.                                
  76.                                 // 发送数据
  77.                                 xhr.send(jsonData);
  78.                                 // 注释掉就会爆 POST 错误提示
  79.                                 //4、接收及处理响应结果,当服务器响应成功了再获取
  80.                                 xhr.onreadystatechange = function() { //当xmlhttp对象就绪状态改变时会触发事件
  81.                                         if (xhr.readyState == 4 && xhr.status == 200) { //请求已完成且响应就绪,响应状态码为200
  82.                                                 alert(xhr.responseText);
  83.                                                 console.log("检测的正确的返回\n");
  84.                                         }else{
  85.                                                 console.log("检测到错误的返回\n");
  86.                                         }
  87.                                         console.log("检测到返回函数\n");
  88.                                 };
  89.                                
  90.                         }
  91.                 </script>
  92.         </head>
  93.         <body>
  94.                 <input type="button" value="发送异步请求" onclick="fun();">
  95.                 <input type="text">
  96.         </body>
  97. </html>
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4