Android How to - Consume Web Service








Question

We would like to know how to consume Web Service.

Answer

/*  ww  w.  j  a v  a 2  s .c  om*/
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

class UtilTelAddress {

  public static String getAddress(String mobile) {
    try {
      String soap = "data";
      byte[] entity = soap.getBytes();

      String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
      HttpURLConnection conn = (HttpURLConnection) new URL(path)
          .openConnection();
      conn.setConnectTimeout(5000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type",
          "application/soap+xml; charset=utf-8");
      conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
      conn.getOutputStream().write(entity);
      if (conn.getResponseCode() == 200) {
        return parseSOAP(conn.getInputStream());
      }
    } catch (Exception e) {
      return null;
    }
    return null;
  }

  private static String parseSOAP(InputStream xml) throws Exception {
    XmlPullParser pullParser = Xml.newPullParser();
    pullParser.setInput(xml, "UTF-8");
    int event = pullParser.getEventType();
    while (event != XmlPullParser.END_DOCUMENT) {
      switch (event) {
      case XmlPullParser.START_TAG:
        if ("getMobileCodeInfoResult".equals(pullParser.getName())) {
          return pullParser.nextText();
        }
        break;
      }
      event = pullParser.next();
    }
    return null;
  }

}