开发者

Buffered Reader Returns Null

Hi i开发者_如何学Python send an ajax call to server like this

$.ajax({
    type: 'POST',
    url: "...",
    dataType:'json',
    data:JSON.stringify(contact),
    success:function(){
        alert("success")
    }

At server i handle this request and trying to read the json object from request like this.

StringBuilder sb = new StringBuilder();
try {
        BufferedReader br = new BufferedReader(new 
InputStreamReader(request.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
    }

but br.readLine() returns null. Any idea why it happens?


Because you reached the end of the stream.

From the JavaDocs:

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Very likely an empty result is returned, the problem is somewhere else then. I don't know if the AJAX request is send as a body of the request, or as a POST parameter. Use request.getParameter("json") instead might help, but check with LiveHttpHeaders first, how your browser encodes the request and which parameter name is bound to the data. In this case you don't have to work with readline at all.


I tested it and there is no problem with how you use the HTTP request InputStream. The 'contact' element is most likely undefined at the time of the request. Therefore it is converted to an empty JSON string. Try adding some fixed text to the 'data' field and you should see it working on server side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜