編輯:關於 Android 程式設計
本文為子墨原創,轉載請註明出處!https://blog.csdn.net/zimo2013/article/details/38037989
在〈Android WebServices 介紹〉一文中,我們簡單介紹了 WebServices 的基礎知識,本篇則深入分析 ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar 的實作源碼。
public void getRemoteInfo(String phoneSec) {
String nameSpace = "https://WebXml.com.cn/";
String methodName = "getMobileCodeInfo";
String endPoint = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
String soapAction = "https://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. 核心方法調用,soapAction 在 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());
}
}
call 方法是整個呼叫流程的心臟,主要完成以下幾件事:
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");
requestDump = debug ? new String(requestData) : null;
responseDump = null;
// 建立連線(可指定超時時間)
ServiceConnection connection = getServiceConnection();
connection.setRequestProperty("User-Agent", USER_AGENT);
// SOAPAction 不是 VER12 的有效標頭,因此 VER12 時不加入
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);
}
connection.setRequestProperty("Accept-Encoding", "gzip");
// 加入使用者自訂標頭
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;
int contentLength = 8192;
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);
if (null == hp.getKey()) {
continue;
}
if (hp.getKey().equalsIgnoreCase("content-length")) {
if (hp.getValue() != null) {
try {
contentLength = Integer.parseInt(hp.getValue());
} catch (NumberFormatException nfe) {
contentLength = 8192;
}
}
}
if (hp.getKey().equalsIgnoreCase("Content-Type") && hp.getValue().contains("xml")) {
xmlContent = true;
}
if (hp.getKey().equalsIgnoreCase("Content-Encoding") && hp.getValue().equalsIgnoreCase("gzip")) {
gZippedContent = true;
}
}
// 首先檢查響應碼
if (status != 200) {
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) {
// ... 錯誤串流處理,避免把 HTTP 錯誤串流當成 SOAP 回應解析
}
if (debug) {
is = readDebug(is, contentLength, outputFile);
}
// 根據 is 流,將流數據解析至 envelope.bodyIn 中
parseResponse(envelope, is, retHeaders);
// 釋放資源
is = null;
buf = null;
connection.disconnect();
connection = null;
return retHeaders;
}
整段流程可濃縮為:先把 envelope 序列化為請求位元組,設定各項 HTTP 標頭後以 POST 送出;接著讀取響應碼與標頭,判斷是否為 gzip 壓縮或 XML 內容;最後透過 parseResponse 把響應串流解析回 envelope.bodyIn,完成整個 request/response 循環。理解這個流程,除錯與效能調校都會更得心應手。
實例下載:https://download.csdn.net/detail/strawberry2013/7663399
Android 自訂特效:用 Canvas 與插值器實作水波紋擴散
水波紋特效大家應該都不陌生,印象中大略有幾種類型:支付類 App 的「咻咻咻」擴散圈、流量監控那種球體的「蕩漾」感,以及真正模擬物理水波、需要處理 Bitmap 的寫實版
Android ListView 分頁刷新實作:滑動到底自動加載更多
分頁刷新的使用場景當列表資料量很大時,若一次載入全部內容,可能造成等待時間過長、記憶體使用量偏高,也影響使用者體驗。因此,許多 App 會採用分頁加載:先顯示第一頁,當使
Android shape 標籤用法完整整理
shape 用來定義形狀,可以在 selector、layout 等資源檔中引用。它底下有六個子標籤,分別負責圓角、漸層、間距、大小、填色與描邊。 完整的語法範本 &l
Socket 實戰:Android 手機客戶端與 PC 服務端的區域網路聯調
本文示範如何把 Android 客戶端與 PC 上的 Java 服務端放在同一個區域網路內完成聯機測試。測試環境包含三個角色:PC 服務器、Android 平板客戶端、以