所以我打算做一个应用程序,为你提供当前所在位置的天气。现在我知道了我的当前坐标,并编写了以下代码:
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!";
}
}请注意,该url是有效的,尽管我在此处替换了我的appid。
每次我运行这段代码时,TextView都会显示“你又失败了!”。
为什么?
(附注:我在Manifest中确实有足够的用户权限)
发布于 2016-09-29 08:24:29
我建议使用一个库来提出你的网络请求,这将为你省去很多麻烦。以http://square.github.io/retrofit/为例查看Retrofit
https://stackoverflow.com/questions/39759492
复制相似问题