Weather API和HttpURLConnection

时间:2016-09-29 00:18:56

标签: java android httpurlconnection openweathermap

所以我打算制作一款应用程序,为您提供当前位置的天气。现在我知道我当前的坐标,并编写了以下代码:

MainActivity.java

//..... (previous codes obtain the coordinate, and working)
RetrieveWeather mRetrieveWeather = new RetrieveWeather();
t.append("" + mRetrieveWeather.getWeatherReport(mCoordinate));

RetrieveWeather.java

package com.example.maest.weather;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by maest on 2016/9/28.
 */
public class RetrieveWeather {
        public String getWeatherReport(double[] mCoordinate){
        HttpURLConnection mHttpUrlConnection = null;
        InputStream mInputStream = null;

        try{
            mHttpUrlConnection = (HttpURLConnection) (new URL("http://api.openweathermap.org/data/2.5/forecast?lat=38.868884&lon=-77.053086&appid=myid)).openConnection();
            mHttpUrlConnection.setRequestMethod("GET");
            mHttpUrlConnection.setDoInput(true);
            mHttpUrlConnection.connect();

            StringBuffer mStringBuffer = new StringBuffer();
            mInputStream = mHttpUrlConnection.getInputStream();
            BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
            String mString = null;
            while ((mString = mBufferedReader.readLine()) != null)
                mStringBuffer.append(mString + "\n");

            mInputStream.close();
            mHttpUrlConnection.disconnect();
            return mStringBuffer.toString();
        }catch (Throwable t){
            t.printStackTrace();
        }finally{
            try { mInputStream.close();}catch(Throwable t) {}
            try { mHttpUrlConnection.disconnect();}catch(Throwable t) {}
        }

        return "You failed again!";
    }
}

请注意,虽然我在此处替换了我的appid,但网址仍然有效。

每次运行此代码时,TextView都会显示“您再次失败!”。

为什么???

(p.s。我在Manifest中有足够的用户权限)

1 个答案:

答案 0 :(得分:0)

您无法在主线程上发出网络请求。这可能是问题,虽然很难说没有看到结果打印堆栈跟踪。我建议使用库来制作网络请求,这样可以省去很多麻烦。查看Retrofit,例如http://square.github.io/retrofit/