我是 android 开发新手,我正在尝试制作 HTTPConnection。我制作了两个文件,一个是 ParsingActivity.java(主活动文件),另一个是 XMLParser.java(用于设置 HTTPRClient 请求)。
ParserActivity.java
package ok.done;
import android.app.Activity;
import android.os.Bundle;
public class ParsingActivity extends Activity {
String URL = "http://api.androidhive.info/pizza/?format=xml";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("t1==========>"+URL);
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
System.out.println("t2==========>"+xml);
}
}
XMLParsing.java
package ok.done;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class XMLParser {
// constructor
public XMLParser() {
}
public String getXmlFromUrl(String url) {
String xml = null;
System.out.println("t3==========>"+xml);
System.out.println("t4==========>"+url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("t5==========>"+url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
System.out.println("t6==========>"+xml);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
}
我还在 AndroidManifest.xml 中添加了权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ok.done"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".ParsingActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
我的 System.out.println 的 LogCat 结果是
对于 t1==========>http://api.androidhive.info/pizza/?format=xml t3==========>null t4======= ===>http://api.androidhive.info/pizza/?format=xml t5==========>null t6==========>null t2=== =======>空
但是如果在我这个简单的代码中一切都是完美的,那么 t6,t2 的结果就是 xml 文件描述。
任何人请建议我应该做什么或任何其他有助于我创建 XML 解析类型应用程序的链接。
提前致谢。