Android Studio:从可在浏览器中使用的URL获取FileNotFoundException

问题描述

我正在开发一个应用程序,该应用程序使用JSON格式从URL获取信息。直到昨天,我的代码都可以正常工作,但是现在,尽管我没有进行任何更改,但它仍然没有运行。 启用明文通信,并设置了Android Internet权限。 我收到FileNotFoundException,但该URL在我的浏览器中有效。

 java.io.FileNotFoundException: http://www.omdbapi.com/?apikey=[myKey]&i=tt6475636

我得到响应代码403,并通过getErrorStream()得到:

buffer(com.android.okhttp.okio.GzipSource@27e5e03).inputStream()

这是我的代码

private class getPlot extends AsyncTask<String,Void,String> {
    
    protected String doInBackground(String... strings) {
        
        String plot = "";
        HttpURLConnection urlConn = null;
        BufferedReader bufferedReader = null;

        try{
            String movieByID="http://www.omdbapi.com/?apikey=[myKey]&i=tt6475636";

            URL url = new URL(movieByID);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML,like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            urlConn.connect();
            int status = urlConn.getResponseCode();
            if(status >= 400 && status <= 499) {
                System.out.println(status);
                InputStream error = urlConn.getErrorStream();
                System.out.println(error);
            } else {

            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); *Exception comes with this Line*
            StringBuilder stringBuffer = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            JSONObject jo1 = new JSONObject(stringBuffer.toString());
            plot = jo1.getString("Plot");
            }
            return plot;
        } catch(Exception ex) {
            Log.e("App","getPlot",ex);
            return null;
        }
        finally {
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printstacktrace();
                }
            }
        }
    }

Logcat基地是:

2020-10-20 15:33:59.454 7506-7506/? I/s.nfr: Not late-enabling -Xcheck:jni (already on)
2020-10-20 15:33:59.535 7506-7506/? W/s.nfr: Unexpected cpu variant for X86 using defaults: x86
2020-10-20 15:33:59.854 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden method Landroid/graphics/drawable/Drawable;->getopticalInsets()Landroid/graphics/Insets; (light greylist,linking)
2020-10-20 15:33:59.854 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist,linking)
2020-10-20 15:33:59.854 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist,linking)
2020-10-20 15:33:59.854 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist,linking)
2020-10-20 15:33:59.854 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist,linking)
2020-10-20 15:33:59.938 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist,reflection)
2020-10-20 15:33:59.938 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist,reflection)
2020-10-20 15:33:59.952 7506-7506/com.depaes.nfr W/s.nfr: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist,linking)
2020-10-20 15:34:00.156 7506-7536/com.depaes.nfr D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config     debugBuild: true
2020-10-20 15:34:00.172 7506-7506/com.depaes.nfr D/Openglrenderer: Skia GL Pipeline
2020-10-20 15:34:00.223 7506-7538/com.depaes.nfr D/HostConnection: HostConnection::get() New Host Connection established 0xe8949280,tid 7538
2020-10-20 15:34:00.228 7506-7538/com.depaes.nfr D/HostConnection:     HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
2020-10-20 15:34:00.231 7506-7538/com.depaes.nfr I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColordisplay retrieved: 0
2020-10-20 15:34:00.231 7506-7538/com.depaes.nfr I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRdisplay retrieved: 0
2020-10-20 15:34:00.231 7506-7538/com.depaes.nfr I/Openglrenderer: Initialized EGL,version 1.4
2020-10-20 15:34:00.231 7506-7538/com.depaes.nfr D/Openglrenderer: Swap behavior 1
2020-10-20 15:34:00.231 7506-7538/com.depaes.nfr W/Openglrenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED,retrying without...
2020-10-20 15:34:00.232 7506-7538/com.depaes.nfr D/Openglrenderer: Swap     behavior 0
2020-10-20 15:34:00.262 7506-7538/com.depaes.nfr D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
2020-10-20 15:34:00.262 7506-7538/com.depaes.nfr D/EGL_emulation: eglCreateContext: 0xe89052a0: maj 3 min 0 rcv 3
2020-10-20 15:34:00.300 7506-7538/com.depaes.nfr D/EGL_emulation: eglMakeCurrent: 0xe89052a0: ver 3 0 (tinfo 0xe89032e0)
2020-10-20 15:34:00.318 7506-7538/com.depaes.nfr D/HostConnection: createUnique: call
2020-10-20 15:34:00.318 7506-7538/com.depaes.nfr D/HostConnection: HostConnection::get() New Host Connection established 0xe8949550,tid 7538
2020-10-20 15:34:00.322 7506-7538/com.depaes.nfr D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
2020-10-20 15:34:00.322 7506-7538/com.depaes.nfr E/eglCodecCommon: GoldfishAddressspaceHostMemoryAllocator: ioctl_ping Failed for device_type=5,ret=-1
2020-10-20 15:34:00.383 7506-7536/com.depaes.nfr I/System.out: 403
2020-10-20 15:34:00.383 7506-7536/com.depaes.nfr I/System.out: buffer(com.android.okhttp.okio.GzipSource@eddd3fe).inputStream()
2020-10-20 15:34:00.477 7506-7538/com.depaes.nfr D/EGL_emulation: eglMakeCurrent: 0xe89052a0: ver 3 0 (tinfo 0xe89032e0)
2020-10-20 15:34:00.482 7506-7538/com.depaes.nfr D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 3 2

解决方法

URL返回状态码404,因此未创建输入流,因为它为null。将URLConnection替换为HttpURLConnection,并在创建输入流之前检查其状态

替换

URLConnection urlConn = null;
URL url = new URL(movieByID);
urlConn =  url.openConnection();

使用

HttpURLConnection urlConn = null;
URL url = new URL(movieByID);
urlConn = (HttpURLConnection) url.openConnection();

现在您可以处理响应代码并实现if-else语句

if (responseCode >= 400 && responseCode <= 499) {
  // response is null
} else {
  // create an input stream
}