【问题标题】:Android - Read JSON from POST requestAndroid - 从 POST 请求中读取 JSON
【发布时间】:2017-07-06 15:28:59
【问题描述】:

我需要从 Android 中的 POST 请求中捕获 JSON 响应。

这是我目前的代码:

String data = null;
    try {
        data = URLEncoder.encode("Field1", "UTF-8") 
                + "=" + URLEncoder.encode(field1, "UTF-8");
        data += "&" + URLEncoder.encode("Field2", "UTF-8") + "="
                   + URLEncoder.encode(field2, "UTF-8"); 
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

       String text = "";
       BufferedReader reader=null;

       // Send data 
          try
          { 

              // Defined URL  where to send data
              URL url = new URL(Constants.URL_EMAIL_LOGIN);

           // Send POST data request

            HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
            wr.write(data); 
            wr.flush(); 
            int number = conn.getResponseCode();

            // Get the server response

          reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line = null;

          // Read Server Response
          while((line = reader.readLine()) != null)
              {
                     // Append server response in string
                     sb.append(line + "\n");
              }


              text = sb.toString();
          }
          catch(Exception ex)
          {

          }
          finally
          {
              try
              {

                  reader.close();
              }

              catch(Exception ex) {}
          }

如果 ResponseCode 是 200(一切正常),服务器会向我发送一个包含我需要的数据的字符串。没问题,我发布的代码可以毫无问题地处理它。 200 响应:

"{\r\n  \"user\": \"AAAA\",\r\n  \"token\": \" \",\r\n  \"email\": \"test@test.com\" \r\n}"

但我还需要捕捉错误。在这种情况下,服务器返回一个JSON。这是一个错误的响应(我使用 Firefox 的海报扩展得到它):

{"Message":"Field1 is not correct."}

有了这个响应,我的应用程序在这一行崩溃了:

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

这是捕获的错误:

java.io.FileNotFoundException: [url]

有谁知道我如何从服务器读取JSON

【问题讨论】:

    标签: android json post


    【解决方案1】:

    错误是由conn.getInputStream() 方法引起的。如果服务器返回的响应代码大于或等于400,则HttpUrlConnection 会在getInputStream() 上引发FileNotFoundException 异常

    当响应状态不是200时,使用conn.getErrorStream()获取输入流
    检查这个:

    BufferedInputStream inputStream = null;
    
    int status = conn.getResponseCode();
    
    if (status != HttpURLConnection.HTTP_OK) {
        inputStream = conn.getErrorStream();
    } else {
        inputStream = conn.getInputStream();
    }
    

    并在你的reader 中使用它:

    reader = new BufferedReader(new InputStreamReader(inputStream));
    

    【讨论】:

    • @O.D.我很高兴它有帮助!
    猜你喜欢
    • 2018-06-20
    • 2020-04-06
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多