Chrome扩展程序对我的Java服务器

时间:2017-08-26 12:28:21

标签: javascript java google-chrome google-chrome-extension xmlhttprequest

这是我在StackOverflow上发布的第一个问题。我通常倾向于为任何项目找到任何问题的答案,但我真的被困在这个问题上。我正在编写一个Chrome扩展程序,尝试通过HTTP发布请求将JSON对象与其中的某些数据一起发送到基本Java服务器,该服务器将在稍后阶段处理某些数据并返回HTTP响应客户的相关(已处理)信息。这是客户端的相关JavaScript代码段:

function postRequest(jsonObject) {
    var param = JSON.stringify(jsonObject);
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
         if (request.readyState == 4) {
             console.log(request.response);
         }
    };
    request.open("POST", "http://"+link);
    request.setRequestHeader("Content-type","text/plain");
    request.send(param);
    // request.abort();
}

输入JSON对象是合法的,link-item是服务器的预定义主机IP。服务器端代码是基于Java的,如下所示:

public class Server {
public static void main(String args[]) throws Exception {
    while (true) {
        try {
            ServerSocket ss = new ServerSocket(1024);
            Socket s = ss.accept();
            System.out.println("Request: ");
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter pw = new PrintWriter(s.getOutputStream());
            String line;
            while ((line = br.readLine()) != null) {
                if (line.length() == 0) {
                    break;
                }
                System.out.print(line + "\r\n");
            }
            System.out.println("");
            System.out.println("Response:");
            String response = "HTTP/1.1 200 OK \r\n" + "Access-Control-Allow-Origin: * \r\n"
                    + "Connection: close \r\n" + "\r\n";
            System.out.println(response);
            pw.write(response);
            while ((line = br.readLine()) != null) {
                if (line.length() == 0) {
                    break;
                }
                System.out.print(line + "\r\n");
            }
            br.close();
            pw.close();
            System.out.println("");
            System.out.println("Socket Closed");
            System.out.println("");
            s.close();
            ss.close();
        } catch (Exception ex) {
            // Do whatever
        }
    }
}}

服务器确实接收到请求和JSON对象,但客户端没有收到响应(readyState通常为4,但状态代码为0,responseText为空)。此外,当我不使用request.abort()或关闭扩展程序的窗口时,连接不会关闭。它肯定与清单文件中的权限无关,所以我没有在这篇文章中包含它。有人能看出我的错误是什么,或者有没有人有类似的经历?

编辑: 服务器端收到HTTP请求,如下所示:

POST / HTTP/1.1
Host: [IP address of the server; I deleted the exact address for privacy]
Connection: keep-alive 
Content-Length: 173
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Origin: chrome-extension://nhpingbdjkkljheamibjobneeehiednk
Content-type: text/plain
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2

由于在服务器端收到请求,我认为实际发送的响应当前不成功。它可能与客户端的原始域有关吗?当我在浏览器中复制粘贴该域时,我得到一个ERR_FILE_NOT_FOUND。

0 个答案:

没有答案