后端 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/78704783
public 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() {
@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 = "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-Headers
httpExchange.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() {
@Override
public 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) { //请求已完成且响应就绪,响应状态码为200
alert(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>