今天,简单讲讲android如何在网络请求时通过post方式发送xml数据。

其实也很简单,不过我之前对网络请求这一块不太熟悉,当需要做这个发送xml数据时,居然不知道怎么做。后来,在网上查找资料,最终是解决了问题。这里记录一下。


一.通过HttpURLConnection发送xml数据

因为原理很简单,直接举例子。

其中发送的xml数据为:

<?xml version = “1.0” ?> SeqID CommandID ABSCDSDFChargeMSISDNSPID Code < IDtype > IDtype 0 ID 0

返回的xml数据为:

<?xml version = “1.0” ?>   SeqID ResultCode0

然后进行解析,代码如下,参考一下,对于以后再做post请求的时候,做参考

class httpThread implements Runnable {    /* (non-Javadoc)     * @see java.lang.Runnable#run()     */    @Override    public void run() {        // TODO Auto-generated method stub        //组建xml数据        StringBuilder xml = new StringBuilder();        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");        xml.append("");        xml.append("");        xml.append("13333333333");        xml.append("1");        xml.append("1333333333");        xml.append("1333333333");        xml.append("3510127");        xml.append("");        xml.append("0");        xml.append("135000000000000216559");        xml.append("");        xml.append("");        try {            byte[] xmlbyte = xml.toString().getBytes("UTF-8");                        System.out.println(xml);            URL url = new URL("http://118.85.194.28:8080/sotpms_server/GetSSOMessage");                                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setConnectTimeout(5000);            conn.setDoOutput(true);// 允许输出            conn.setDoInput(true);            conn.setUseCaches(false);// 不使用缓存            conn.setRequestMethod("POST");            conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接            conn.setRequestProperty("Charset", "UTF-8");            conn.setRequestProperty("Content-Length",                    String.valueOf(xmlbyte.length));            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");            conn.setRequestProperty("X-ClientType", "2");//发送自定义的头信息            conn.getOutputStream().write(xmlbyte);            conn.getOutputStream().flush();            conn.getOutputStream().close();            if (conn.getResponseCode() != 200)                throw new RuntimeException("请求url失败");            InputStream is = conn.getInputStream();// 获取返回数据                            // 使用输出流来输出字符(可选)            ByteArrayOutputStream out = new ByteArrayOutputStream();            byte[] buf = new byte[1024];            int len;            while ((len = is.read(buf)) != -1) {                out.write(buf, 0, len);            }            String string = out.toString("UTF-8");            System.out.println(string);            out.close();                                                  // xml解析            String version = null;            String seqID = null;            XmlPullParser parser = Xml.newPullParser();            try {                parser.setInput(new ByteArrayInputStream(string.substring(1)                        .getBytes("UTF-8")), "UTF-8");                 parser.setInput(is, "UTF-8");                int eventType = parser.getEventType();                while (eventType != XmlPullParser.END_DOCUMENT) {                    if (eventType == XmlPullParser.START_TAG) {                        if ("SSOMessage".equals(parser.getName())) {                            version = parser.getAttributeValue(0);                        } else if ("SeqID".equals(parser.getName())) {                            seqID = parser.nextText();                        } else if ("ResultCode".equals(parser.getName())) {                            resultCode = parser.nextText();                        }                    }                    eventType = parser.next();                }            } catch (XmlPullParserException e) {                e.printStackTrace();                System.out.println(e);            } catch (IOException e) {                e.printStackTrace();                System.out.println(e);            }            System.out.println("version = " + version);            System.out.println("seqID = " + seqID);            System.out.println("resultCode = " + resultCode);*/        } catch (Exception e) {            // TODO Auto-generated catch block            System.out.println(e);        }    }

简单讲讲,其实就是HttpURLConnection 的http请求头部设置和xml数据相关的内容,比较重要的是conn.setRequestProperty("Content-Length",String.valueOf(xmlbyte.length));数据长度为xml字符串的长度。conn.getOutputStream().write(xmlbyte);直接发送xml数据。最后解析返回的xml数据,我之前写了如何解析xml数据的博客,大家可以看看。


二.通过httpClient Post方式提交xml

也直接举一个例子:

package com.javaeye.wangking717.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;public class HttpConnectionUtil {private final static Log logger = LogFactory.getLog(HttpConnectionUtil.class);public static String postSOAP(String url, String soapContent) {HttpClient httpclient = null;HttpPost httpPost = null;BufferedReader reader = null;int i = 0;while (i < 4) {try {httpclient = new DefaultHttpClient();httpPost = new HttpPost(url);StringEntity myEntity = new StringEntity(soapContent, "UTF-8");httpPost.addHeader("Content-Type", "text/xml; charset=UTF-8");httpPost.setEntity(myEntity);HttpResponse response = httpclient.execute(httpPost);HttpEntity resEntity = response.getEntity();if (resEntity != null) {reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));StringBuffer sb = new StringBuffer();String line = null;while ((line = reader.readLine()) != null) {sb.append(line);sb.append("\r\n");}return sb.toString();}} catch (Exception e) {i++;if (i == 4) {logger.error("not connect:" + url + "\n" + e.getMessage());}} finally {if (httpPost != null) {httpPost.abort();}if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}if (httpclient != null) {httpclient.getConnectionManager().shutdown();}}}return "none";}public static void main(String[] args) {String url = "http://localhost:8080/opgtest/servlet/MyTest";String soap = "\r\n"+ "\r\n"+ "传递过来的内容\r\n" + "\r\n"+ "";System.out.println(postSOAP(url, soap));}}

也简单讲讲,主要是通过StringEntity stringEntity = new StringEntity(xml,"UTF-8");将xml数据变成StringEntity ,然后通过httpPost.setEntity(stringEntity);将StringEntity设置到httpPost。最后直接response = httpclient.execute(httpPost);发送数据。这个比起HttpURLConnection要简单很多,建议使用这一种代码。


android http通过post请求发送一个xml就讲完了。


就这么简单。

更多相关文章

  1. Android之TextView设置String文本颜色
  2. 第一行代码 Android(安卓)第 2 版 读书笔记
  3. Android中实现Native与H5的通信方案汇总
  4. Android(安卓)笔记38: BAIDU MAP API GPS数据定位偏移校正
  5. eclipse 上调试android的自带应用方法 一
  6. 第一个Android(安卓)程序的源代码: TxtReader文本阅读器
  7. Android中AsyncTask的执行过程
  8. 实例详解Android文件存储数据方式
  9. Android4.0下的Calendar、events、reminder简单Demo

随机推荐

  1. Android数据存储之SQLite
  2. Android 仿美团外卖底部顶起 lottie 封装
  3. 【android】ImageView的src和background
  4. Android------播放音乐的工具类
  5. 浅谈Android中的Handler
  6. 创建自定义视图在Android矩阵效果画布教
  7. Android中Activity、Service和线程之间的
  8. 基于 Android NDK 的学习之旅-----数据传
  9. Android入门教程(二十三)------之Gallery
  10. 基于Android的Word文档阅读器