HttpURLConnection以FileNotFoundException(404)而不是401返回响应

时间:2017-01-24 09:53:20

标签: java android spring http

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

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();

1 个答案:

答案 0 :(得分:4)

试试这段代码。

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