android http通过post请求发送一个xml
今天,簡單講講android如何在網(wǎng)絡(luò)請求時(shí)通過post方式發(fā)送xml數(shù)據(jù)。
其實(shí)也很簡單,不過我之前對(duì)網(wǎng)絡(luò)請求這一塊不太熟悉,當(dāng)需要做這個(gè)發(fā)送xml數(shù)據(jù)時(shí),居然不知道怎么做。后來,在網(wǎng)上查找資料,最終是解決了問題。這里記錄一下。
一.通過HttpURLConnection發(fā)送xml數(shù)據(jù)
因?yàn)樵砗芎唵?#xff0c;直接舉例子。
其中發(fā)送的xml數(shù)據(jù)為:
<?xml version = “1.0” ?> <SSOMessage version=”1.0”> <SSOParas> <SeqID>SeqID</SeqID> <CommandID>CommandID</CommandID> <MSISDN>ABSCDSDF</MSISDN> <ChargeMSISDN>ChargeMSISDN</ChargeMSISDN> <SPID>SPID</SPID> <Code> Code </ Code > < IDtype > IDtype 0</ IDtype > <ID> ID 0</ID> </SSOParas> </SSOMessage>返回的xml數(shù)據(jù)為:
<?xml version = “1.0” ?> <SSOMessage version=”1.0”> <SSOParas> <SeqID>SeqID</SeqID> <ResultCode>ResultCode0</ResultCode> </SSOParas> </SSOMessage>然后進(jìn)行解析,代碼如下,參考一下,對(duì)于以后再做post請求的時(shí)候,做參考
class httpThread implements Runnable {/* (non-Javadoc)* @see java.lang.Runnable#run()*/@Overridepublic void run() {// TODO Auto-generated method stub//組建xml數(shù)據(jù)StringBuilder xml = new StringBuilder();xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");xml.append("<SSOMessage version=\"1.0\">");xml.append("<SSOParas>");xml.append("<SeqID>13333333333</SeqID>");xml.append("<CommandID>1</CommandID>");xml.append("<MSISDN>1333333333</MSISDN>");xml.append("<ChargeMSISDN>1333333333</ChargeMSISDN>");xml.append("<SPID>3510127</SPID>");xml.append("<Code></Code>");xml.append("<IDtype>0</IDtype>");xml.append("<ID>135000000000000216559</ID>");xml.append("</SSOParas>");xml.append("</SSOMessage>");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");//發(fā)送自定義的頭信息conn.getOutputStream().write(xmlbyte);conn.getOutputStream().flush();conn.getOutputStream().close();if (conn.getResponseCode() != 200)throw new RuntimeException("請求url失敗");InputStream is = conn.getInputStream();// 獲取返回?cái)?shù)據(jù)// 使用輸出流來輸出字符(可選)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 blockSystem.out.println(e);}}簡單講講,其實(shí)就是HttpURLConnection 的http請求頭部設(shè)置和xml數(shù)據(jù)相關(guān)的內(nèi)容,比較重要的是conn.setRequestProperty("Content-Length",String.valueOf(xmlbyte.length));數(shù)據(jù)長度為xml字符串的長度。conn.getOutputStream().write(xmlbyte);直接發(fā)送xml數(shù)據(jù)。最后解析返回的xml數(shù)據(jù),我之前寫了如何解析xml數(shù)據(jù)的博客,大家可以看看。
二.通過httpClient Post方式提交xml
也直接舉一個(gè)例子:
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 = "<xml>\r\n"+ "<body>\r\n"+ "傳遞過來的內(nèi)容\r\n" + "</body>\r\n"+ "</xml>";System.out.println(postSOAP(url, soap));}}也簡單講講,主要是通過StringEntity stringEntity = new StringEntity(xml,"UTF-8");將xml數(shù)據(jù)變成StringEntity ,然后通過httpPost.setEntity(stringEntity);將StringEntity設(shè)置到httpPost。最后直接response = httpclient.execute(httpPost);發(fā)送數(shù)據(jù)。這個(gè)比起HttpURLConnection要簡單很多,建議使用這一種代碼。
android http通過post請求發(fā)送一個(gè)xml就講完了。
就這么簡單。
總結(jié)
以上是生活随笔為你收集整理的android http通过post请求发送一个xml的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android http协议添加Auth
- 下一篇: android setGravity()