我是Android的新手,对代码的理解非常有限。我试图从互联网上的api返回xml数据。我已经阅读了几个关于这个但是似乎没有用的东西,它们对代码几乎没有解释,所以我无法改变它太多。
有人可以解释我哪里出错了,并就需要改变的地方给我一些指导吗?
干杯球员
package com.example.testingXML;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet();
httpget.setURI(new URI("http://api.inapub.co.uk/venues/postcode/bn23fe/1/?API_Key=7xa3tdmjkhu6jwjvp746zgg4"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
String NL = System.getProperty("line.separator");
while((line = r.readLine()) != null){
total.append(line + NL);
}
r.close();
String page = r.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
两件事:
1)请使用单独的线程进行HTTP提取。看到: http://developer.android.com/reference/android/os/AsyncTask.html
2)确保您的应用程序正在请求互联网权限
<uses-permission android:name="android.permission.INTERNET" />
3)最简单的方法是使用URLConnection
URLConnection conn = new URL("http://api.inapub.co.uk/venues/postcode [etc...]").OpenConnection();