【问题标题】:Catch 404 JSON response instead of crashing捕获 404 JSON 响应而不是崩溃
【发布时间】:2015-04-30 11:40:32
【问题描述】:

我有一个 Android 应用程序,它是为响应一个响应 JSON 响应的网络查询而编写的。当查询格式正确时,一切正常。但是,当查询错误时,代码崩溃,我在堆栈跟踪中得到以下信息:

java.io.FileNotFoundException: https://******

我已将***** 代替我在此处放置的隐私查询。

如果我在浏览器中输入相同的查询,我会得到以下响应:

{"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}

我的问题是 - 为什么我的代码会抛出错误,而不是将其视为可以解析的有效 JSON 响应?

这是我的代码:

@Override
protected String doInBackground(String... params) {

try {



URL u = new URL(params[0]);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setRequestMethod("GET");
    conn.connect();
    InputStream is = conn.getInputStream();

    // Read the stream              

    byte[] b = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    while ( is.read(b) != -1) {
            baos.write(b);
    }

    String JSONResp = new String(baos.toByteArray());

        return JSONResp;
    }
    catch(Throwable t) {
        t.printStackTrace();
    }
    return null;
}

【问题讨论】:

    标签: android json http http-status-code-404


    【解决方案1】:

    您可以使用以下代码检查 httpurlconnection 对象的状态代码:

     if(conn.getResponseCode()==HttpURLConnection.HTTP_ACCEPTED)
                {
                    //handle the accepted response
                }
                else
                {
                    //handle the failed response
                }
    

    【讨论】:

      【解决方案2】:

      您应该使用getErrorStream() 来读取后端调用的错误流

      在出现错误时从服务器返回输入流 因为在远程服务器上找不到请求的文件。这 流可用于读取服务器将发回的数据。

      InputStream is = null;
      if (responseCode == 200) {
        is = urlConnection.getInputStream();
      } else {
        is = urlConnection.getErrorStream();
      }
      

      【讨论】:

        【解决方案3】:

        改为使用以下代码获取 json 响应表单服务器:

         private InputStream is = null;
           private String jsonString = "";
           private JSONObject jsonObj = null;
        
            public JSONObject getJSONFromUrl(final String url) { //url is your url
        
                    try {
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(url);
        
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
        
                        is = httpEntity.getContent();
        
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                    try {
        
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                is, "iso-8859-1"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();
                        if (sb.length() != 0)
                            jsonString = sb.toString();
                    } catch (Exception e) {
                        Log.e("_TAG", "Buffer Error: " + e.getMessage());
                    }
                    try {
                        jsonObj = new JSONObject(jsonString);
                    } catch (JSONException e) {
                        Log.e("_TAG", "Parsing Error: " + e.getMessage());
                    }
                    return jsonObj;
                }
        

        现在通过上述方法从返回的jsonObj中获取statusCode

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-17
          相关资源
          最近更新 更多