安卓:HttpUrlConnection对象连接后返回301错误

3
我将翻译如下内容:

我试图使用URL连接到一个Web API。但是,当我尝试在浏览器中访问提供的URL时,没有任何错误。然而,我从服务器接收到了301错误(永久移动)

以下是构建URL的代码:

 public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        String minMagnitude = sharedPrefs.getString(
                getString(R.string.settings_min_magnitude_key),
                getString(R.string.settings_min_magnitude_default));

        String orderBy = sharedPrefs.getString(
                getString(R.string.settings_order_by_key),
                getString(R.string.settings_order_by_default)
        );

        Uri baseUri = Uri.parse(USGS_REQUEST_URL);
        Uri.Builder uriBuilder = baseUri.buildUpon();

        uriBuilder.appendQueryParameter("format", "geojson");
        uriBuilder.appendQueryParameter("limit", "10");
        uriBuilder.appendQueryParameter("minmag", minMagnitude);
        uriBuilder.appendQueryParameter("orderby", orderBy);
        Log.i ("the uri is ", uriBuilder.toString());
        return new EarthquakeLoader(this, uriBuilder.toString());
    }

这里是尝试连接URL所代表资源的代码:

private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        // If the URL is null, then return early.
        if (url == null) {
            return jsonResponse;
        }
        Log.i("The received url  is " , url +"");
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // If the request was successful (response code 200),
            // then read the input stream and parse the response.
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); //this log returns 301
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // Closing the input stream could throw an IOException, which is why
                // the makeHttpRequest(URL url) method signature specifies than an IOException
                // could be thrown.
                inputStream.close();
            }
        }
        return jsonResponse;
    }

从提供的日志中,当状态码不是200时,我可以知道连接返回了301状态码。我还记录了生成的URL,我从logcat中复制并在浏览器中尝试过,它运行良好。这是构建的URL:http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=10&minmag=6&orderby=magnitude 我查看了这个问题:Android HttpURLConnection receives HTTP 301 response code,但我不清楚问题的解决方案。
请帮我识别和解决问题。
更新:如greenapps在他的评论中指出,连接是通过https完成的。该评论确定了问题并帮助我修复代码。
在我的代码中,我用于构建基本URL的字符串具有http而不是https协议值,它是:
private static final String USGS_REQUEST_URL =
            "http://earthquake.usgs.gov/fdsnws/event/1/query";

阅读了greenapps的评论后,我将字符串中的协议部分更改为https,因此变成了:

 private static final String USGS_REQUEST_URL =
            "https://earthquake.usgs.gov/fdsnws/event/1/query"; 

问题解决了。

谢谢。


如果你在这里点击你的http链接,你会看到浏览器显示一个https页面。最好直接使用那个URL,因为现在有重定向。 - greenapps
@ greenapps 谢谢你的评论!你的评论帮助我找到了解决方案。正如你所说,它使用 https,我检查了用于构建初始 URL 的基本字符串,并发现我正在使用 http,我只是将其修改为 https,然后它就非常好用了。非常感谢。如果您愿意,可以将其发布为答案,然后我会接受它。 - Dania
2个回答

4

如果您在此处点击您的http链接,那么浏览器会显示一个https页面。最好直接使用该网址,因为现在有重定向。


1
这是因为地址从http转换到https。 为了避免这种情况,您需要将请求地址转换为https。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接