Android程序如何调用webservice

来源:互联网 发布:打码源码 编辑:程序博客网 时间:2024/05/17 03:43

本文以获取天气预报为例

  • URL: http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx
  • 调用方法: getWeather

使用HttpURLConnection组拼XML调用

新建URL对象,获取HttpURLConnection对象.

URL url = new URL("http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx");HttpURLConnection cnn = (HttpURLConnection) url.openConnection();

设置HttpURLConnection对象属性

cnn.setDoInput(true);cnn.setDoOutput(true);cnn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");cnn.setRequestMethod("POST");cnn.setConnectTimeout(5000);

根据该服务提供的请求和响应示例组拼SOAP请求

OutputStream ops = cnn.getOutputStream();StringBuffer buffer = new StringBuffer(5000);buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")....append(edtxt.getText().toString())....append("</getWeather></soap:Body></soap:Envelope>");ops.write(buffer.toString().getBytes());

将返回的XML读到StringBuilder对象中

int code = cnn.getResponseCode();if(code == 200){    InputStream ios = cnn.getInputStream();    int length = 0;    byte b[] = new byte[1024];    StringBuilder builder = new StringBuilder();    while((length=ios.read(b))!=-1){        String s = new String(b,0,length);        builder.append(s);    }...}else{//请求失败...}

下载完整代码

使用ksoap2调用

参考网友博客使用ksoap2 调用 WebService(实例:调用天气预报服务)

p.s 由于.net对soap的具体实现有细微差别,本人尝试ksoap2调用.net的webservice未能成功.

0 0
原创粉丝点击