Android - 向服务器发送发布请求时的例外情况

时间:2017-01-13 11:14:34

标签: java android json post request

在我的android项目中,我有一个用于向我的服务器发出HTTP请求的类。我有sendGet,sendPost和sendPut的方法。以下是sendPost方法的代码:

public JSONObject sendPost(String urlString, String urlParameters) {

        URL url;
        JSONObject jObj = null;
        String json = "";

        try{

            url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();

            json = sb.toString();

        } catch (MalformedURLException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }

        try{
            jObj = new JSONObject(json);
        }
        catch (JSONException e){
            e.printStackTrace();
        }

        System.out.println(jObj);

        return jObj;

    }

它应该将服务器响应作为JSONObject返回。如果我发送帖子到我的服务器,我会得到以下例外:

java.io.FileNotFoundException: http://...(在我创建BufferedReader的行中)

org.json.JSONException: End of input at character 0 of(在我做的行中jObj = new JSONObject(json);)

但如果我将网址复制到我的浏览器中,则没有任何问题。似乎一切正常,因为我的服务器已收到并处理了请求。但是为什么我得到这些错误并且结果是一个空的JSONObject?

修改

在我的node.js服务器上,我按以下格式发送回复:

res.status(200).json({ success: "true" });

res.status(400).json({ success: "false", message:"..." });

编辑2:

在@greenapps评论之后我改变了我的代码:

    ...
    json = sb.toString();
    jObj = new JSONObject(json);

    br.close();
    wr.flush();
    wr.close();

} catch (MalformedURLException e){
    e.printStackTrace();
}
catch (IOException e){
    e.printStackTrace();
}
catch (JSONException e){
    e.printStackTrace();
}

return jObj;

现在JSONException消失了,但FileNotFoundException仍然存在,并且返回时jObj仍为空。

1 个答案:

答案 0 :(得分:0)

我的node.js服务器中有一个错误,服务器的响应代码是502.而BufferedReader只能使用200状态代码。这就是我得到例外的原因。现在我在BufferedReader周围有一个if:

if(connection.getResponseCode() == 200) {

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder sb = new StringBuilder();

    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }

    json = sb.toString();
    jObj = new JSONObject(json);

    br.close();
}else{
    json = "{ success: \"false\" }";
    jObj = new JSONObject(json);
}
相关问题