java http接收数据精简版

使用原生 java 与原生 js

html部分

html 复制代码
<!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() {
				// 创建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.open('POST', 'http://mygamefoundation.all123.net:8080/', true);
				// xhr.open('POST', 'https://cn-sx-bgp-tmp1.natfrp.cloud:20504/', true);
				// xhr.open('POST', 'www.baidu.com', true);
				// 设置请求头
				xhr.setRequestHeader('Content-Type', 'application/json');

				console.log("请求头已设置\n");
				// 监听服务器响应

				// 构建JSON对象
				var data = {
					name: 'John',
					age: 25,
					email: 'john@example.com'
				};

				// 将JSON对象转换为字符串
				var jsonData = JSON.stringify(data);

				// 发送数据
				// xhr.send(jsonData);
				// 所有的 send 注释掉就会爆 POST 错误提示
				// xhr.send("6655ookk\n");
				let sendText = document.getElementById("message").value
				
				xhr.send(sendText);
				
				//4、接收及处理响应结果,当服务器响应成功了再获取
				xhr.onreadystatechange = function() { //当xmlhttp对象就绪状态改变时会触发事件
					if (xhr.readyState == 4 && xhr.status == 200) { //请求已完成且响应就绪,响应状态码为200
						alert(xhr.responseText);
						console.log(xhr.responseText);
						console.log("检测的正确的返回\n");
						// 把数据写进网页里,动态增加数据
						// https://blog.csdn.net/jerrcy_fly/article/details/69367264
						// document.write(xhr.responseText);
						// document.write("<h1 id=\"h2\">通过document.write输出内容</h1>");

						// 动态追加数据
						// https://segmentfault.com/q/1010000007420031
						var element = document.getElementById("div1");
						var para = document.createElement("p");
						var node = document.createTextNode("这是新段落。");
						var nodev2 = document.createTextNode(xhr.responseText);
						para.appendChild(node);
						para.appendChild(nodev2);
						element.appendChild(para);

					} else {
						console.log("检测到错误的返回\n");
					}
					console.log("检测到返回函数\n");
				};

			}
		</script>
		
<!-- 这里注释的脚本不会执行 -->
<!-- 	<script>
		var para = document.createElement("p");
		var node = document.createTextNode("这是新段落。");
		para.appendChild(node);

		var element = document.getElementById("div1");
		element.appendChild(para);
	</script> -->

	</head>
	<body>
		<input type="button" value="发送异步请求" onclick="fun();">
		<input type="text" id="message">
		<div id="div1">
			<p>old</p>
		</div>
	</body>
	<!-- 在nody之后放置脚本就会在后面增加数据 可见在body之后执行数据-->
	<script>
		var para = document.createElement("p");
		var node = document.createTextNode("这是新段落。");
		para.appendChild(node);

		var element = document.getElementById("div1");
		element.appendChild(para);
	</script>
</html>

java服务器部分

java 复制代码
package Httpv3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class freshHttp {
	public static void main() throws IOException {
//		创建服务器,绑定端口
		HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
//		绑定消息检测,"/"表示接收所有来源的消息,例如"/aa"是接收aa开头的消息
		httpServer.createContext("/", new MyHttpHandler());
		// 启动服务
		httpServer.start();
	}
//	只有在内部static 才行
	static class MyHttpHandler implements HttpHandler {
		@Override
		public 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 = ("<?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("Access-Control-Allow-Origin", "*");
			httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "*");
//			httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
			httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
			// 设置响应code和内容长度
			httpExchange.sendResponseHeaders(200, respContents.length);

			// 设置响应内容
			httpExchange.getResponseBody().write(respContents);
//			接收请求数据
			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);

			// 关闭处理器
			httpExchange.close();
		}
	}
}
相关推荐
冷琴19963 分钟前
基于java+springboot的酒店预定网站、酒店客房管理系统
java·开发语言·spring boot
巽星石23 分钟前
【Blender Python】7.一些运算、三角函数以及随机
python·blender·三角函数·随机·环形阵列
CSXB9924 分钟前
一、Python(介绍、环境搭建)
开发语言·python·测试工具·集成测试
GOTXX25 分钟前
应用层协议HTTP
linux·网络·网络协议·计算机网络·http·fiddler
Mopes__27 分钟前
Python | Leetcode Python题解之第461题汉明距离
python·leetcode·题解
daiyang123...30 分钟前
IT 行业的就业情况
java
EterNity_TiMe_1 小时前
【机器学习】智驭未来:探索机器学习在食品生产中的革新之路
人工智能·python·机器学习·性能优化·学习方法
爬山算法1 小时前
Maven(6)如何使用Maven进行项目构建?
java·maven
.生产的驴1 小时前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
爱学的小涛1 小时前
【NIO基础】基于 NIO 中的组件实现对文件的操作(文件编程),FileChannel 详解
java·开发语言·笔记·后端·nio