Android_WebServices_介绍一文中,简介了WebServices的基础知识。以下主要分析 ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar实现源代码。

1.调用WebServices流程

public void getRemoteInfo(String phoneSec) {
String nameSpace = "http://WebXml.com.cn/";
String methodName = "getMobileCodeInfo";
String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo"; // 1.初始化 SoapObject对象。为该方法设置參数。相当于信体
SoapObject request = new SoapObject(nameSpace, methodName);
request.addProperty("mobileCode", phoneSec);
request.addProperty("userId", ""); // 2.实例化SoapSerializationEnvelope对象,相当于信皮
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
envelope.bodyOut = request;
envelope.dotNet = true;//兼容.net开发的Net-Services // 3.实例化HttpTransportSE对象,还能够指定放了訪问的请求时间
HttpTransportSE transport = new HttpTransportSE(endPoint);
//HttpTransportSE transport = new HttpTransportSE(endPoint, timeout);
try {
// 4.核心方法调用,当中soapActon在SoapSerializationEnvelope.VER12时无效,且为POST请求
transport.call(soapAction, envelope); SoapObject response = (SoapObject) envelope.bodyIn;
final String result = response.getProperty(0).toString();//Vector
toast(result);
} catch (Exception e) {
e.printStackTrace();
toast(e.getMessage());
}
}

2.transport.call关键源代码分析

/**
* Perform a soap call with a given namespace and the given envelope providing
* any extra headers that the user requires such as cookies. Headers that are
* returned by the web service will be returned to the caller in the form of a
* <code>List</code> of <code>HeaderProperty</code> instances.
*
* @param soapAction
* the namespace with which to perform the call in.
* @param envelope
* the envelope the contains the information for the call.
* @param headers
* <code>List</code> of <code>HeaderProperty</code> headers to send with the SOAP request.
* @param outputFile
* a file to stream the response into rather than parsing it, streaming happens when file is not null
*
* @return Headers returned by the web service as a <code>List</code> of
* <code>HeaderProperty</code> instances.
*
* @throws HttpResponseException
* an IOException when Http response code is different from 200
*/
public List call(String soapAction, SoapEnvelope envelope, List headers, File outputFile)
throws HttpResponseException, IOException, XmlPullParserException { if (soapAction == null) {
soapAction = "\"\"";
} //依据envelope,将其序列化为一个请求字节数组
byte[] requestData = createRequestData(envelope, "UTF-8"); // debug=true, requestDump的值为请求的数据,方便调试
requestDump = debug ? new String(requestData) : null;
responseDump = null; //connection = new ServiceConnectionSE(proxy, url, timeout);包含设置时间
ServiceConnection connection = getServiceConnection(); connection.setRequestProperty("User-Agent", USER_AGENT);
// SOAPAction is not a valid header for VER12 so do not add
// it
// @see "http://code.google.com/p/ksoap2-android/issues/detail? id=67
if (envelope.version != SoapSerializationEnvelope.VER12) {
connection.setRequestProperty("SOAPAction", soapAction);
} if (envelope.version == SoapSerializationEnvelope.VER12) {
connection.setRequestProperty("Content-Type", CONTENT_TYPE_SOAP_XML_CHARSET_UTF_8);
} else {
connection.setRequestProperty("Content-Type", CONTENT_TYPE_XML_CHARSET_UTF_8);
} // this seems to cause issues so we are removing it
//connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Accept-Encoding", "gzip"); // Pass the headers provided by the user along with the call
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
HeaderProperty hp = (HeaderProperty) headers.get(i);
connection.setRequestProperty(hp.getKey(), hp.getValue());
}
} // POST请求
connection.setRequestMethod("POST");
//发送数据。耗时较长,将requestData发送至connection的输出流
sendData(requestData, connection, envelope); requestData = null;
InputStream is = null;
List retHeaders = null;
byte[] buf = null; // To allow releasing the resource after used
int contentLength = 8192; // To determine the size of the response and adjust buffer size
boolean gZippedContent = false;
boolean xmlContent = false;
// 得到响应码
int status = connection.getResponseCode(); try {
//得到响应头
retHeaders = connection.getResponseProperties(); for (int i = 0; i < retHeaders.size(); i++) {
HeaderProperty hp = (HeaderProperty)retHeaders.get(i);
// HTTP response code has null key
if (null == hp.getKey()) {
continue;
} // If we know the size of the response, we should use the size to initiate vars
if (hp.getKey().equalsIgnoreCase("content-length") ) {
if ( hp.getValue() != null ) {
try {
contentLength = Integer.parseInt( hp.getValue() );
} catch ( NumberFormatException nfe ) {
contentLength = 8192;
}
}
} // Check the content-type header to see if we're getting back XML, in case of a
// SOAP fault on 500 codes
if (hp.getKey().equalsIgnoreCase("Content-Type")
&& hp.getValue().contains("xml")) {
xmlContent = true;
} // ignoring case since users found that all smaller case is used on some server
// and even if it is wrong according to spec, we rather have it work..
if (hp.getKey().equalsIgnoreCase("Content-Encoding")
&& hp.getValue().equalsIgnoreCase("gzip")) {
gZippedContent = true;
}
} //first check the response code....
if (status != 200) {
//throw new IOException("HTTP request failed, HTTP status: " + status);
throw new HttpResponseException("HTTP request failed, HTTP status: " + status, status);
} if (contentLength > 0) {
if (gZippedContent) {
is = getUnZippedInputStream(
new BufferedInputStream(connection.openInputStream(),contentLength));
} else {
is = new BufferedInputStream(connection.openInputStream(),contentLength);
}
}
} catch (IOException e) {
if (contentLength > 0) {
if(gZippedContent) {
is = getUnZippedInputStream(
new BufferedInputStream(connection.getErrorStream(),contentLength));
} else {
is = new BufferedInputStream(connection.getErrorStream(),contentLength);
}
} if ( e instanceof HttpResponseException) {
if (!xmlContent) {
if (debug && is != null) {
//go ahead and read the error stream into the debug buffers/file if needed.
readDebug(is, contentLength, outputFile);
} //we never want to drop through to attempting to parse the HTTP error stream as a SOAP response.
connection.disconnect();
throw e;
}
}
} // debug=true responseDump=响应数据,方便调试
if (debug) {
is = readDebug(is, contentLength, outputFile);
} // 依据is流,将流数据解析至 envelope.bodyIn中去
parseResponse(envelope, is,retHeaders); //释放资源
is = null;
buf = null;
connection.disconnect();
connection = null;
// 返回响应头
return retHeaders;
}

实例下载http://download.csdn.net/detail/strawberry2013/7663399

Android_WebServices_源代码分析的更多相关文章

  1. android-plugmgr源代码分析

    android-plugmgr是一个Android插件加载框架,它最大的特点就是对插件不需要进行任何约束.关于这个类库的介绍见作者博客,市面上也有一些插件加载框架,但是感觉没有这个好.在这篇文章中,我 ...

  2. Twitter Storm源代码分析之ZooKeeper中的目录结构

    徐明明博客:Twitter Storm源代码分析之ZooKeeper中的目录结构 我们知道Twitter Storm的所有的状态信息都是保存在Zookeeper里面,nimbus通过在zookeepe ...

  3. 转:SDL2源代码分析

    1:初始化(SDL_Init()) SDL简介 有关SDL的简介在<最简单的视音频播放示例7:SDL2播放RGB/YUV>以及<最简单的视音频播放示例9:SDL2播放PCM>中 ...

  4. 转:RTMPDump源代码分析

    0: 主要函数调用分析 rtmpdump 是一个用来处理 RTMP 流媒体的开源工具包,支持 rtmp://, rtmpt://, rtmpe://, rtmpte://, and rtmps://. ...

  5. 转:ffdshow 源代码分析

    ffdshow神奇的功能:视频播放时显示运动矢量和QP FFDShow可以称得上是全能的解码.编码器.最初FFDShow只是mpeg视频解码器,不过现在他能做到的远不止于此.它能够解码的视频格式已经远 ...

  6. UiAutomator源代码分析之UiAutomatorBridge框架

    上一篇文章<UIAutomator源代码分析之启动和执行>我们描写叙述了uitautomator从命令行执行到载入測试用例执行測试的整个流程.过程中我们也描写叙述了UiAutomatorB ...

  7. MyBatis架构设计及源代码分析系列(一):MyBatis架构

    如果不太熟悉MyBatis使用的请先参见MyBatis官方文档,这对理解其架构设计和源码分析有很大好处. 一.概述 MyBatis并不是一个完整的ORM框架,其官方首页是这么介绍自己 The MyBa ...

  8. hostapd源代码分析(三):管理帧的收发和处理

    hostapd源代码分析(三):管理帧的收发和处理 原文链接:http://blog.csdn.net/qq_21949217/article/details/46004379 这篇文章我来讲解一下h ...

  9. hostapd源代码分析(二):hostapd的工作机制

    [转]hostapd源代码分析(二):hostapd的工作机制 原文链接:http://blog.csdn.net/qq_21949217/article/details/46004433 在我的上一 ...

随机推荐

  1. Google Chrome 39.0.2171.71 正式发布

    Google Chrome,又称Google浏览器,是一个由Google(谷歌)公司开发的网页浏览器.该浏览器是基于其他开源软件所撰写,包括WebKit,目标是提升稳定性.速度和安全性,并创造出简单且 ...

  2. 简单Gif制作

    没什么需求,只是循环图片的推荐:http://gif.55.la/ ,在线制作,无需下载

  3. python笔记18-sort和sorted区别

    前言 python的排序有两个方法,一个是list对象的sort方法,另外一个是builtin函数里面sorted,主要区别: sort仅针对于list对象排序,无返回值, 会改变原来队列顺序 sor ...

  4. Java垃圾回收精粹 — Part2

    Java垃圾回收精粹分4个部分,本篇是第2部分.在第2部分里介绍了Hotspot中的堆结构.对象分配以及次要回收. Hotspot中的堆结构 理解不同的收集器的工作方式,是探讨Java堆结构如何支持分 ...

  5. 解决sqoop报错Invalid number; item = ITEM_UNICODE

    报错栈: java.sql.SQLException: Invalid number; item = ITEM_UNICODE at com.intersys.jdbc.SysList.getInt( ...

  6. xml布局内容总结(一)--Android

    关于安卓项目中xml的使用非常多.为了达到一些好的UI效果.须要对xml比較熟练.会使用非常多的小技巧,本人准备对这些小技巧进行整理和总结,希望进行分享和交流. 关于weight的使用,因为weigh ...

  7. [Android Studio] Android Studio如何提示函数用法

    Eclipse有一个很好的功能,就是当你代码调用某个android API时,鼠标移到对应的函数或者方法上,就会自动有一个悬 浮窗提示该函数的说明(所包含的参数含义,该方法功能).迁移到Android ...

  8. 1)Linux程序设计入门--基础知识

    )Linux程序设计入门--基础知识 Linux下C语言编程基础知识 前言: 这篇文章介绍在LINUX下进行C语言编程所需要的基础知识.在这篇文章当中,我们将 会学到以下内容: 源程序编译 Makef ...

  9. Python学习(八)异常处理

    Python 异常处理 程序出错时,会抛出异常,这想必在之前学习过程中已经见过不少. 这边具体说明下Python 的标准异常.如何捕捉异常.抛出异常 以及自定义异常. python 标准异常 我们先来 ...

  10. dTree无限级文件夹树和JQuery同步Ajax请求

    曾经都是用JQuery对树的支持来实现文件夹树的,近来闲来无事就弄了下dTree,感觉其无限级文件夹还是挺好的,并且它的使用也比較方便,基本上就是先把要用的js文件即dtree.js和css文件dtr ...