简单的Java HTTP服务器应用程序,以JSONP形式响应。

huangapple go评论81阅读模式
英文:

Simple Java HTTP Server application that responds in JSONP

问题

以下是翻译好的内容:

我想创建一个非常简单的HTTP服务器使用Java并进行JSONP响应
以下是代码

public static void main(String[] args) throws Exception {
     HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
     HttpContext context = server.createContext("/test");
     context.setHandler(Sample::handleRequest);
     server.start();
     System.out.println("服务器已启动,端口号:8500");
}

private static void handleRequest(HttpExchange exchange) throws IOException {
     JSONObject json = new JSONObject("{\"weight\":\"23400\"}");
     exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
     exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
     exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
     exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
     exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
     exchange.sendResponseHeaders(200, json.toString().getBytes().length);
     OutputStream os = exchange.getResponseBody();
     os.write(json.toString().getBytes());
     os.close();
}

客户端代码:

$(document).ready(function () {
    $.ajax({
        url: 'http://localhost:8500/test/',
        type: "GET",
        dataType: "jsonp",
        data: { no: 120 },
        contentType: 'application/json',
        success: function (data) {
            $('#txtWeight').val(data);
        },
        error: function (err) {
            console.log(err);
        }
    });
});

我遇到的问题与HTTP处理程序有关。Chrome返回:
跨源读取阻止(CORB)阻止了带有文本/纯文本 MIME 类型的跨源响应 http://localhost:8500/test/?callback=jQuery34109210173679568667_1603222391566&no=120&_=1603222391567

请您查看一下,告诉我是否有什么问题?

英文:

I want to create a very simple HTTP server Java with JSONP responds.
Here is the code:

public static void main(String[] args) throws Exception {
	 HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
      HttpContext context = server.createContext("/test");
      context.setHandler(Sample::handleRequest);
      server.start();
	 System.out.println("Server started on port 8500");
    }	 
 
 private static void handleRequest(HttpExchange exchange) throws IOException {
      JSONObject json = new JSONObject("{\"weight\":\"23400\"}");
      exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
      exchange.getResponseHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
      exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
      exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      exchange.getResponseHeaders().set("contentType", "application/json; charset=UTF-8");
      exchange.sendResponseHeaders(200, json.toString().getBytes().length);
      OutputStream os = exchange.getResponseBody();
      os.write(json.toString().getBytes());
      os.close();
  }

and client:

$(document).ready(function () {
        $.ajax({
            url: 'http://localhost:8500/test/',
            type: "GET",
            dataType: "jsonp",
            data: { no: 120 },
            contentType: 'application/json',
            success: function (data) {
                $('#txtWeight').val(data);
            },
            error: function (err) {
                console.log( err);
            }
        });
    });

The problem that I have is related to the HTTP Handler. The Chrome returns:
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:8500/test/?callback=jQuery34109210173679568667_1603222391566&no=120&_=1603222391567 with MIME type text/plain

Could you please have a look and tell me if something is wrong?

答案1

得分: 1

你需要将代码中的"*"替换为你在标头中收到的"Origin"。问题与Chrome相关,与Java无关。

private static void handleRequest(final HttpExchange exchange) throws IOException {
    final String json = "{\"weight\":\"23400\"}";
    final String origin = exchange.getRequestHeaders().getFirst("Origin");
    if (origin != null) exchange.getResponseHeaders().add("Access-Control-Allow-Origin", origin);
    exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
    exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
    exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
    exchange.sendResponseHeaders(200, json.getBytes().length);
    try (OutputStream os = exchange.getResponseBody()) {
        os.write(json.getBytes());
        os.flush();
    }
    exchange.close();
}
英文:

you need to replace "*" with the "Origin" you received in the header.
The problem is Chrome related and not java related.

		private static void handleRequest(final HttpExchange exchange) throws IOException {
	final String json = "{\"weight\":\"23400\"}";
	final String origin = exchange.getRequestHeaders().getFirst("Origin");
	if(origin != null) exchange.getResponseHeaders().add("Access-Control-Allow-Origin", origin);
	exchange.getResponseHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
	exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
	exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
	exchange.getResponseHeaders().set("contentType", "application/json; charset=UTF-8");
	exchange.sendResponseHeaders(200, json.getBytes().length);
	try(OutputStream os = exchange.getResponseBody()) {
		os.write(json.getBytes());
		os.flush();
	}
	exchange.close();
}

huangapple
  • 本文由 发表于 2020年10月21日 03:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64452358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定