我是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结果是
for t1 ==========&gt; http://api.androidhive.info/pizza/?format = xml T3 ==========&GT;空 T4 ==========&GT; HTTP://api.androidhive.info/pizza/格式= XML T5 ==========&GT;空 T6 ==========&GT;空 T2 ==========&GT;空
但是如果我的这个简单代码中的所有东西都是完美的,则t6的结果是t2,t2是xml文件描述。
任何一个PLZ建议我应该做什么或任何其他链接对我来说有助于创建XML解析类型应用程序。
提前致谢。
答案 0 :(得分:0)
您确定http服务器在触发后提供有效的xml。要确保在Web浏览器上触发URL,如果服务器提供了xml,您将获得xml内容。