繁体   English   中英

使用JAVA套接字服务器读取AJAX发布内容

[英]Read AJAX post content using JAVA socket server

我设置了一个JAVA套接字服务器,该服务器能够从html <form>获取所有内容。 但是当涉及到AJAX发布时,服务器只能获取POST事件,但不能读取AJAX发布中的“数据”。 以下是html代码:

HTML

<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>

<script type="text/javascript">
$(document).ready(function() {
     $('#submit').click(function() {
//information to be sent to the server

info = $('#foo').val();
$.ajax({
  type: "POST",
  url: 'http://10.0.0.3:8888',
  data: ({foo: info}),
  //crossDomain: true,
  dataType: 'json'
});

return false;       
});

});
</script>

</head>
<body>

<label>Text</label>
<textarea id="foo"></textarea>

<button id="submit">Submit via Ajax</button>

</body>
</html>

我不知道为什么会这样,有什么建议吗?

谢谢

-------------------------------------------------- -------------------------------------------

更新

Java服务器代码

    ServerSocket ss = new ServerSocket(8888);
    Socket s = ss.accept();

    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

    String inputLine;
    while (!(inputLine = in.readLine()).equals(""))
        System.out.println(inputLine);

    PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
    pw.println("aa");

    s.close();
    ss.close();

我在服务器上得到的是:

POST / HTTP/1.1
Host: 10.109.3.184:8888
Connection: keep-alive
Content-Length: 58
Accept: */*
Origin: xxxxxxxxxxxxxxxxxx
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: xxxxxxxxxxxxxxxxxx
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4

内容没有出现...

HTTP请求中的POST数据作为请求正文出现,该请求正文以空行与head分开,如下所示:

POST / HTTP/1.1
Host: 10.0.1.1:80
Connection: keep-alive
Content-Length: 29
Content-Type: text/json

{"id":123,"name":"something"}

因此,您的服务器代码应该( 或多或少 );-)如下所示:

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

String line;
List<String> headers = new LinkedList<>();
StringBuilder body = null;
while ((line = in.readLine()) != null) {
    //- Here we test if we've reach the body part.
    if (line.isEmpty() && body == null) {
        body = new StringBuilder();
        continue;
    }
    if (body != null) {
        body.append(line).append('\n');
    }
    else {
        headers.add(line);
    }
}

System.out.println("--- Headers ---");
for (String h : headers) {
    System.out.println(h);
}
System.out.println("--- Body ---");
System.out.println(body != null ? body.toString() : "");

请注意,该代码仅用于测试目的。 您不能假设该正文是文本(至少您应该验证Content-Type标头),并且可以安全地将其读取到StringBuilder中,或者可以完全将其整体加载到内存中(至少应该验证Content) -长度标头)。 尽管有这些标头,但您应该预料到最坏的情况,并且在阅读过程中会执行一些健全性检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM