Android中HTTP通信和XML解析

来源:互联网 发布:网络业务员管理办法 编辑:程序博客网 时间:2024/04/28 23:44

 转自 http://www.apkbus.com/android-854-1-1.html


我们要记住的就是HTTP通信与服务端做HTTP通信,分别以 GET 方式和POST 方式做演示。XML 解析可以用两种方式解析 XML,分别是 DOM 方式和 SAX方式。异步消息处理 - 通过 Handler 实现异步消息处理,以一个自定义的异步下载类来说明 Handler 的用法。现在我们大家应该明白HTTPxml了吧,那我们就来看看代码是怎么写的吧,代码中有注释。下面的代码很长大家可要仔细看。


Java代码:
  1. package EOE.android.cc;

  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12. import java.util.Map;

  13. import javax.xml.parsers.DocumentBuilder;
  14. import javax.xml.parsers.DocumentBuilderFactory;
  15. import javax.xml.parsers.SAXParser;
  16. import javax.xml.parsers.SAXParserFactory;

  17. import org.apache.http.HttpEntity;
  18. import org.apache.http.HttpResponse;
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;
  20. import org.apache.http.client.methods.HttpPost;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import org.apache.http.message.BasicNameValuePair;
  23. import org.apache.http.protocol.HTTP;
  24. import org.apache.http.util.ByteArrayBuffer;
  25. import org.apache.http.util.EncodingUtils;
  26. import org.w3c.dom.Document;
  27. import org.w3c.dom.Element;
  28. import org.w3c.dom.NodeList;
  29. import org.xml.sax.InputSource;
  30. import org.xml.sax.XMLReader;

  31. import android.app.Activity;
  32. import android.os.Bundle;
  33. import android.view.View;
  34. import android.widget.Button;
  35. import android.widget.TextView;

  36. public class Main extends Activity {

  37. private TextView textView;

  38. /** Called when the activity is first created. */
  39. @Override
  40. public void onCreate(Bundle savedInstanceState) {
  41. super.onCreate(savedInstanceState);
  42. setContentView(R.layout.main);

  43. textView = (TextView) this.findViewById(R.id.textView);

  44. Button btn1 = (Button) this.findViewById(R.id.btn1);
  45. btn1.setText("http get demo");
  46. btn1.setOnClickListener(new Button.OnClickListener() {
  47. public void onClick(View v) {
  48. httpGetDemo();
  49. }
  50. });

  51. Button btn2 = (Button) this.findViewById(R.id.btn2);
  52. btn2.setText("http post demo");
  53. btn2.setOnClickListener(new Button.OnClickListener() {
  54. public void onClick(View v) {
  55. httpPostDemo();
  56. }
  57. });

  58. Button btn3 = (Button) this.findViewById(R.id.btn3);
  59. // DOM - Document Object Model
  60. btn3.setText("DOM 解析 XML");
  61. btn3.setOnClickListener(new Button.OnClickListener() {
  62. public void onClick(View v) {
  63. DOMDemo();
  64. }
  65. });

  66. Button btn4 = (Button) this.findViewById(R.id.btn4);
  67. // SAX - Simple API for XML
  68. btn4.setText("SAX 解析 XML");
  69. btn4.setOnClickListener(new Button.OnClickListener() {
  70. public void onClick(View v) {
  71. SAXDemo();
  72. }
  73. });
  74. }

  75. // Android 调用 http 协议的 get 方法
  76. // 本例:以 http 协议的 get 方法获取远程页面响应的内容
  77. private void httpGetDemo(){
  78. try {
  79. // 模拟器测试时,请使用外网地址
  80. URL url = new URL("http://xxx.xxx.xxx");
  81. URLConnection con = url.openConnection();

  82. String result = "http status code: " + ((HttpURLConnection)con).getResponseCode() + "\n";
  83. // HttpURLConnection.HTTP_OK

  84. InputStream is = con.getInputStream();
  85. BufferedInputStream bis = new BufferedInputStream(is);
  86. ByteArrayBuffer bab = new ByteArrayBuffer(32);
  87. int current = 0;
  88. while ( (current = bis.read()) != -1 ){
  89. bab.append((byte)current);
  90. }
  91. result += EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);

  92. bis.close();
  93. is.close();

  94. textView.setText(result);
  95. } catch (Exception e) {
  96. textView.setText(e.toString());
  97. }
  98. }

  99. // Android 调用 http 协议的 post 方法
  100. // 本例:以 http 协议的 post 方法向远程页面传递参数,并获取其响应的内容
  101. private void httpPostDemo(){
  102. try {
  103. // 模拟器测试时,请使用外网地址
  104. String url = "http://5billion.com.cn/post.php";
  105. Map<String, String> data = new HashMap<String, String>();
  106. data.put("name", "webabcd");
  107. data.put("salary", "100");

  108. DefaultHttpClient httpClient = new DefaultHttpClient();
  109. HttpPost httpPost = new HttpPost(url);
  110. ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
  111. for (Map.Entry<String, String> m : data.entrySet()) {
  112. postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
  113. }

  114. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, HTTP.UTF_8);
  115. httpPost.setEntity(entity);

  116. HttpResponse response = httpClient.execute(httpPost);

  117. String result = "http status code: " + response.getStatusLine().getStatusCode() + "\n";
  118. // HttpURLConnection.HTTP_OK

  119. HttpEntity httpEntity = response.getEntity();

  120. InputStream is = httpEntity.getContent();
  121. result += convertStreamToString(is);

  122. textView.setText(result);
  123. } catch (Exception e) {
  124. textView.setText(e.toString()); 
  125. }
  126. }

  127. // 以 DOM 方式解析 XML(xml 数据详见 res/raw/employee.xml)
  128. private void DOMDemo(){
  129. try {
  130. DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  131. DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  132. Document doc = docBuilder.parse(this.getResources().openRawResource(R.raw.employee));
  133. Element rootElement = doc.getDocumentElement();
  134. NodeList employeeNodeList = rootElement.getElementsByTagName("employee");

  135. textView.setText("DOMDemo" + "\n");
  136. String title = rootElement.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
  137. textView.append(title);
  138. for (int i=0; i<employeeNodeList.getLength(); i++){
  139. Element employeeElement = ((Element)employeeNodeList.item(i));
  140. String name = employeeElement.getAttribute("name");
  141. String salary = employeeElement.getElementsByTagName("salary").item(0).getFirstChild().getNodeValue();
  142. String dateOfBirth = employeeElement.getElementsByTagName("dateOfBirth").item(0).getFirstChild().getNodeValue();
  143. textView.append("\nname: "+name+" salary: "+salary+" dateOfBirth: " + dateOfBirth);
  144. }
  145. } catch (Exception e) {
  146. textView.setText(e.toString()); 
  147. }
  148. }

  149. // 以 SAX 方式解析 XML(xml 数据详见 res/raw/employee.xml)
  150. // SAX 解析器的实现详见 MySAXHandler.java
  151. private void SAXDemo(){
  152. try {
  153. SAXParserFactory saxFactory = SAXParserFactory.newInstance();
  154. SAXParser parser = saxFactory.newSAXParser();
  155. XMLReader reader = parser.getXMLReader();

  156. MySAXHandler handler = new MySAXHandler();
  157. reader.setContentHandler(handler);
  158. reader.parse(new InputSource(this.getResources().openRawResource(R.raw.employee)));
  159. String result = handler.getResult();
  160. textView.setText("SAXDemo" + "\n");
  161. textView.append(result);
  162. } catch (Exception e) {
  163. textView.setText(e.toString()); 
  164. }
  165. }

  166. // 辅助方法,用于把流转换为字符串
  167. private String convertStreamToString(InputStream is) {
  168. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  169. StringBuilder sb = new StringBuilder(); 

  170. String line = null;
  171. try {
  172. while ((line = reader.readLine()) != null) {
  173. sb.append(line + "\n");
  174. }
  175. } catch (IOException e) {
  176. e.printStackTrace();
  177. } finally {
  178. try {
  179. is.close();
  180. } catch (IOException e) {
  181. e.printStackTrace();
  182. }


  183. return sb.toString();
  184. }
  185. }
复制代码
0 0
原创粉丝点击