使用JAVA套接字服务器读取AJAX帖子内容

时间:2014-02-06 15:53:56

标签: java javascript jquery ajax

我设置了一个JAVA套接字服务器,能够从html<形式>。但是当谈到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 Server代码

    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

内容未出现......

1 个答案:

答案 0 :(得分:1)

HTTP请求中的POST数据来自一个请求体,它与空头分隔,如下所示:

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,或者将它完全加载到内存中是否安全(至少应该验证内容) -Length标题)。尽管有这些标题,你应该期待最坏的情况,并在阅读期间进行一些健全性检查。