Android技术疑问:服务器返回404时,HttpURLConnection仍能获取内容吗?
关于HttpURLConnection处理404响应码的问题
当然可以!即使服务器返回404(资源未找到)的响应码,你依然能通过HttpURLConnection获取到服务器返回的内容——前提是服务器本身在返回404时附带了内容(比如自定义的404错误页面、JSON格式的错误提示等)。
为什么能获取?
HTTP 404只是一个状态标识,用来告诉客户端请求的资源不存在,但很多服务端会在返回这个状态码的同时,返回一段内容(比如美观的错误页面、结构化的错误信息),这些内容都可以通过HttpURLConnection读取到。
结合你的代码修改示例
你原来的代码可以补充响应码判断和流读取的逻辑,确保404时也能拿到内容:
class RetrieveDataTask extends AsyncTask<Void, Void, String> { private Exception exception; protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); responseView.setText(""); } protected String doInBackground(Void... urls) { String urlStr = linkText.getText().toString(); HttpURLConnection urlConnection = null; BufferedReader reader = null; String responseContent = ""; try { URL url = new URL(urlStr); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // 获取响应状态码 int responseCode = urlConnection.getResponseCode(); // 选择对应的输入流:成功状态用正常流,错误状态用错误流 InputStream inputStream; if (responseCode >= 200 && responseCode < 300) { inputStream = urlConnection.getInputStream(); } else { // 404、500等错误状态码走这里 inputStream = urlConnection.getErrorStream(); } // 读取流中的内容 reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } responseContent = sb.toString(); } catch (Exception e) { this.exception = e; } finally { // 记得关闭连接和流,避免资源泄漏 if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return responseContent; } // 别忘了补充onPostExecute方法处理结果 protected void onPostExecute(String result) { progressBar.setVisibility(View.GONE); if (exception != null) { responseView.setText("请求出错:" + exception.getMessage()); } else { responseView.setText(result); } } }
注意事项
- 如果服务器返回404时没有附带任何内容,那你读取到的就是空字符串,这是服务端的配置决定的,和
HttpURLConnection无关。 - 一定要区分
getInputStream()和getErrorStream():规范来说,非2xx的状态码应该使用getErrorStream()来获取内容,部分服务器可能会把错误内容放在getInputStream()里,但为了兼容性,建议按状态码分支处理。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

