百度apistore的天气api
String httpArg = "city=beijing";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String httpUrl = "http://apis.baidu.com/heweather/weather/free";
String httpArg = "city=beijing";
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("apikey","f1375c3a44007cdc331966524783f3ab");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("tag",result+"-------");
}`
就这个,在安卓中返回null。
在Java项目中返回正常
经测试,在Android中也可以正常获取到数据。
Android中获取网络数据需要新开线程,另外还需要在Manifest中添加权限。