HttpURLConnection java.io.FileNotFoundException

前端 未结 3 1597
温柔的废话
温柔的废话 2020-12-07 22:50

The code below works great if I connect to what seems to be Apache servers, however when I try to connect to my .Net server it throws an error. I am guessing it is a header

3条回答
  •  有刺的猬
    2020-12-07 23:37

    You can get a FileNotFoundException from HttpUrlConnection (and OkHttpClient) if your server returns >= HTTPStatus.BAD_REQUEST (400). You should check the status code first to check what stream you need to read.

    int status = connection.getResponseCode();
    
    if(status >= HttpStatus.SC_BAD_REQUEST)
        in = connection.getErrorStream();
    else
        in = connection.getInputStream();
    

    HttpStatus deprecated. Latest syntax seems to be:

    InputStream inputStream;
    int status = urlConnection.getResponseCode();
    
    if (status != HttpURLConnection.HTTP_OK)  {
        inputStream = urlConnection.getErrorStream();
    }
    else  {
        inputStream = urlConnection.getInputStream();
    }
    

提交回复
热议问题