为什么百度apistore的天气api在Java项目中能用而在安卓项目中不能用?
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项目中返回正常
白色的卡妙
9 years, 3 months ago
Answers
经测试,在Android中也可以正常获取到数据。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
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+"-------");
super.run();
}
}.start();
}
Android中获取网络数据需要新开线程,另外还需要在Manifest中添加权限。
ablib
answered 9 years, 3 months ago