OpenWeatherMap REST API始终返回HTTP 301

问题描述 投票:2回答:2

我正在尝试从API(http://samples.openweathermap.org/data/2.5/weather?q=London,uk)处理JSON数据,但我在logcat窗口中获得了此数据:301 Moved Permanently

这是我的班级:

public class MainActivity extends AppCompatActivity {

    public class DownloadTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();

                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }

                return result;


            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("JSON",s);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DownloadTask task = new DownloadTask();
        task.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02");
    }
}
java android android-asynctask httpurlconnection openweathermap
2个回答
1
投票

您是否已授予android studio权限使用AndroidManifest.xml中的INTERNET?


0
投票

我已经使用Postman(尝试一下)来分析会发生什么。

您提供的网址是:http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02。阅读响应,您将发现以下内容:

正文:

<html>

<head>
    <title>301 Moved Permanently</title>
</head>

<body bgcolor="white">
    <center>
        <h1>301 Moved Permanently</h1>
    </center>
    <hr>
    <center>openresty/1.9.7.1</center>
</body>

</html>

原始HTML响应:

HTTP/1.1 301 Moved Permanently
Server: openresty/1.9.7.1
Date: Sun, 07 Jun 2020 10:49:57 GMT
Content-Type: text/html
Content-Length: 190
Connection: keep-alive
Location: https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02

如评论中所述,当您获得HTTP 30x(请参阅:Redirection messages)时,服务器会告诉您您正在调用的url是旧的。如果您希望得到正确的响应,则应遵循(因此是“重定向”消息)服务器在HTTP标头中传递给您的新URL。

您要查找的http标头是Location,即报告此URL:

https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02

通过两个URL进行一些比较,服务器告诉您调用URL的https风格。这是一种常见做法,请始终使用https网址(如果有)。

© www.soinside.com 2019 - 2024. All rights reserved.