无法解析来自服务器的响应

时间:2017-03-26 06:25:28

标签: android json http parsing

我正在做一个简单的登录页面。我发送的是用户名字段和密码字段。我在服务器上看到这些参数正在正确传递,然后服务器返回一个json响应。如果HTTP是200,那么我解析响应并获取消息它工作正常。如果状态为401,如果我尝试解析消息,则立即获得IOException。

protected String doInBackground(String... params) {
            HttpURLConnection conn = null;
            try {

                URL url = new URL("http://192.168.1.91:3000/api/login");

                JSONObject postDataParams = new JSONObject();

                postDataParams.put("username", getUsername());
                postDataParams.put("password", getPassword());

                Log.e("params", postDataParams.toString());

                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(30000 /* milliseconds */);
                conn.setConnectTimeout(30000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                conn.setChunkedStreamingMode(0);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode = conn.getResponseCode();    

                Log.e("responseCode", ""+responseCode);

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line = "";

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    in.close();
                    return result.toString();

                }
                else if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {

                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line = "";

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    in.close();
                    return result.toString();

                }
                else {
                    return new String("false : " + responseCode);
                }
            }  catch (MalformedURLException ex) {
                return new String("false : MalformedURLException ");
            } catch (IOException ex) {
                return new String("false : IOException ");
            } catch (JSONException e) {
                return new String("false : JSONException ");
            } catch (Exception e) {
                return new String("false : Exception1 ");
            } finally {
                if (conn != null) {
                    try {
                        conn.disconnect();
                    } catch (Exception ex) {
                        return new String("false : Exception2 ");
                    }
                }
            }
        }

服务器是一个nodejs服务器,无论HTTP状态如何,它都会返回以下响应:

router.use(function(err, req, res, next) {
  console.log('Message returned ' + err.status + " " + err.message);
    res.status(err.status || params.ERROR_HTTP_INTERNAL).json(JSON.stringify({
        error: err.message
    }));
})

我不认为它与服务器有任何关系,因为当使用邮递员进行REST调用时,我得到了正确的响应代码,我可以看到JSON响应。

3 个答案:

答案 0 :(得分:0)

400表示您的请求中的内容有误。在那种情况下,不会被传回一个身体。您需要找出服务器发回400的原因(如果登录数据无效,它会发送400吗?)。无论如何,不​​要试图在400上解析身体,将其视为错误。

答案 1 :(得分:0)

我找到了答案。由于这是一个错误,我需要改变这个:

InputStream in = new BufferedInputStream(conn.getInputStream());

到此:

InputStream in = new BufferedInputStream(conn.getErrorStream());

答案 2 :(得分:-2)

您最好将okhttp库用于RESTAPI

我想建议学习异步