【问题标题】:HttpURLConnection returns response as FileNotFoundException (404) instead of 401HttpURLConnection 返回响应为 FileNotFoundException (404) 而不是 401
【发布时间】:2017-06-09 01:33:15
【问题描述】:

我的应用程序使用java.net.HttpURLConnection 来获取文件输入流。服务器使用java的spring boot框架。当身份验证令牌过期时,Spring Boot 过滤器抛出 SecurityException 并且我们将响应代码设置为 401,如下所示(Spring Boot 服务器端):

catch (ExpiredJwtException eje) {
            ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.UNAUTHORIZED);
        }

但在 android 端,我们收到异常 FileNotFoundException,它表示 404 和响应代码为 -1。为什么我无法获取响应码为 401 ?

我用来检查响应代码的以下代码(Android 端):

urlConnection.connect();

                if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {

                }

                InputStream inputStream = urlConnection.getInputStream();

【问题讨论】:

  • 我认为你有异常因为 urlConnection.getInputStream()。
  • 如果你的 urlConnection.getResponseCode() 是 401 或 404 你必须使用 urlConnection.getErrorStream();

标签: java android spring http


【解决方案1】:

试试这个代码。

urlConnection.connect();
InputStream inputStream = null;
if(urlConnection.getResponseCode() == 200) {
    inputStream = urlConnection.getInputStream();
}else
{
    inputStream =  urlConnection.getErrorStream()
}

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 2016-04-27
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多