零、概述
項目由于種種原因?qū)е?strong>后臺服務(wù)是用 C# 編寫。請求與返回的數(shù)據(jù)格式是 SOAP 型的 XML 。外加上國內(nèi)外對此描述的文章非常稀少,所以才有了此篇小作文兒。
一、相關(guān)需求
- 解決 SOAP 1.1 或 SOAP 1.2 的 WebService 與 Android 通訊問題。
-
請求、響應(yīng)數(shù)據(jù)格式如下圖
image
二、選擇方案
- 最終選擇使用 SOAP 1.1 用來通訊。 SOAP 1.2 個人未做測試不過感覺原理差不多。
- 使用 simplexml 搭配 Retrofit2 進行 XML 解析。
三、干貨
1.目錄結(jié)構(gòu)

image
PS:原本想把響應(yīng)參數(shù)也抽調(diào)成共通 Base 結(jié)果發(fā)現(xiàn)抽調(diào)后不能正常解析。
2.build.gradle 配置
apply plugin: 'com.android.application'
android {
...
}
dependencies {
...
// Retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'
// XML解析
implementation('com.squareup.retrofit2:converter-simplexml:2.2.0') {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
// FastJson
implementation 'com.alibaba:fastjson:1.2.49'
}
PS:由于早期開發(fā) Java 后臺習慣用 FastJson 來解析 Json ,所以使用了 FastJson 。
3.網(wǎng)絡(luò)模塊
BaseCallBean
/**
* @Description 請求返回基類
*/
public class BaseCallBean<T> {
public boolean success;
public String msg;
public T data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
RetrofitEnum
/**
* @Description 枚舉(用作單例)
*/
public enum RetrofitEnum {
/**
* Retrofit 源
*/
RETROFIT_SOURCE;
private RetrofitManage manage;
RetrofitEnum() {
manage = new RetrofitManage();
}
public RetrofitService getApi() {
return manage.getApi();
}
}
PS:前些日子看到用枚舉特性來實現(xiàn)單例,這里用用。
RetrofitManage
/**
* @Description Retrofit2.0 管理類
*/
public class RetrofitManage {
/**
* HTTP 請求地址
**/
private final String API_URL = "http://192.168.1.200:200";
/**
* 網(wǎng)絡(luò)請求api
*/
private RetrofitService api;
/**
* 構(gòu)造方法
*/
public RetrofitManage() {
// OkHttp3 配置
OkHttpClient client = new OkHttpClient.Builder()
// 連接超時時間
.connectTimeout(7676, TimeUnit.SECONDS)
// 讀取時間
.readTimeout(7676, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
// 服務(wù)器請求URL
.baseUrl(API_URL)
// 轉(zhuǎn)換器方式為XML
.addConverterFactory(SimpleXmlConverterFactory.create())
// OkHttp3 對象
.client(client)
.build();
// 獲取Proxy.newProxyInstance動態(tài)代理對象
api = retrofit.create(RetrofitService.class);
}
/**
* 外部獲取 RetrofitService
* @return ZLRetrofitService
*/
public RetrofitService getApi() {
return api;
}
}
PS:addConverterFactory 這里使用 SimpleXmlConverterFactory 來轉(zhuǎn)換。注意 XML 轉(zhuǎn)換方式與Json轉(zhuǎn)換方式不能同時使用。如果同時加入則先加入的生效。還是來個例子說明一下吧。
EG:下例 Gson 轉(zhuǎn)換生效 XML 不能生效。
Retrofit retrofit = new Retrofit.Builder()
// 服務(wù)器請求URL
.baseUrl(API_URL)
// 添加Gson轉(zhuǎn)換器 需添加依賴 'com.squareup.retrofit2:converter-gson:2.1.0'
.addConverterFactory(GsonConverterFactory.create())
// 轉(zhuǎn)換器方式為XML
.addConverterFactory(SimpleXmlConverterFactory.create())
// OkHttp3 對象
.client(client)
.build();
RetrofitService
/**
* @Description Retrofit 2.0 網(wǎng)絡(luò)請求API
*/
public interface RetrofitService {
// 登錄
@Headers({
"Content-Type: text/xml; charset=utf-8",
"SOAPAction: http://tempuri.org/Login"
})
@POST("LoginService.asmx")
Call<ResLoginEnvelope> login(@Body ReqBaseEnvelope envelope);
}
ReqBaseEnvelope
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
/**
* @Description Envelope
*/
@Root(name = "soap:Envelope")
@NamespaceList({
@Namespace(reference = "http://www.w3.org/2001/XMLSchema", prefix = "xsd"),
@Namespace(reference = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi"),
@Namespace(reference = "http://schemas.xmlsoap.org/soap/envelope/", prefix = "soap")
})
public class ReqBaseEnvelope {
@Element(name = "soap:Body", required = false)
public ReqBaseBody body;
public ReqBaseEnvelope(ReqBaseBody body) {
this.body = body;
}
public ReqBaseBody getBody() {
return body;
}
public void setBody(ReqBaseBody body) {
this.body = body;
}
}
ReqBaseBody
import org.simpleframework.xml.Root;
/**
* @Description Body
*/
@Root(name = "soap:Body")
public interface ReqBaseBody {
}
4.業(yè)務(wù)模塊
ReqLoginBody
import com.demon.soap.http.request.ReqBaseBody;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* @Description 請求登錄 Body
*/
@Root(name = "soap:Body")
public class ReqLoginBody implements ReqBaseBody {
@Element(name = "Login", required = false)
public ReqLoginModel model;
public ReqLoginBody(ReqLoginModel model) {
this.model = model;
}
}
ReqLoginModel
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
/**
* @Description 請求登錄 Model
*/
@Root(name = "Login")
@Namespace(reference = "http://tempuri.org/")
public class ReqLoginModel {
@Element(name = "userName", required = false)
public String userName;
@Element(name = "password", required = false)
public String password;
public ReqLoginModel(String userName, String password) {
this.userName = userName;
this.password = password;
}
}
ResLoginBody
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* @Description 響應(yīng)登錄 Body
*/
@Root(name = "soap:Body")
public class ResLoginBody {
@Element(name = "LoginResponse", required = false)
public ResLoginModel model;
}
ResLoginEnvelope
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
/**
* @Description 響應(yīng)登錄 Envelope
*/
@Root(name = "soap:Envelope")
@NamespaceList({
@Namespace(reference = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi"),
@Namespace(reference = "http://www.w3.org/2001/XMLSchema", prefix = "xsd"),
@Namespace(reference = "http://schemas.xmlsoap.org/soap/envelope/", prefix = "soap")
})
public class ResLoginEnvelope {
@Element(name = "Body", required = false)
public ResLoginBody body;
}
ResLoginModel
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
/**
* @Description 響應(yīng)登錄 返回值
*/
@Root(name = "LoginResponse")
@Namespace(reference = "http://tempuri.org/")
public class ResLoginModel {
@Element(name = "LoginResult")
public String result;
}
activity
...
import com.demon.soap.R;
import com.demon.soap.business.http.request.ReqLoginBody;
import com.demon.soap.business.http.request.ReqLoginModel;
import com.demon.soap.business.http.response.ResLoginEnvelope;
import com.demon.soap.http.BaseCallBean;
import com.demon.soap.http.RetrofitEnum;
import com.demon.soap.http.RetrofitService;
import com.demon.soap.http.request.ReqBaseEnvelope;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @Description : 登錄
*/
public class LoginActivity extends AppCompatActivity {
private Button btnReq;
private TextView tvRes;
// 網(wǎng)絡(luò)請求API
private RetrofitService mApi;
// 接口回調(diào)
private Call<ResLoginEnvelope> mCall;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
initView();
initHttp();
initListener();
}
private void initView() {
btnReq = findViewById(R.id.btn_req);
tvRes = findViewById(R.id.tv_res);
}
private void initHttp() {
mApi = RetrofitEnum.RETROFIT_SOURCE.getApi();
}
private void initListener() {
btnReq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login("admin", "12346");
}
});
}
private void login(String parUserName, String parPassword) {
mCall = mApi.login(new ReqBaseEnvelope(new ReqLoginBody(new ReqLoginModel(parUserName, parPassword))));
mCall.enqueue(new Callback<ResLoginEnvelope>() {
@Override
public void onResponse(Call<ResLoginEnvelope> call, Response<ResLoginEnvelope> response) {
if (null != response.body()) {
Log.d("SOAP", "[login Success Result]:" + response.body().body.model.result);
tvRes.setText(response.body().body.model.result);
// 解析 result Json
BaseCallBean<String> callBean = JSON.parseObject(response.body().body.model.result, new TypeReference<BaseCallBean<String>>() {});
if (callBean.success) {
Toast.makeText(getApplicationContext(), callBean.msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), callBean.msg, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "未請求到數(shù)據(jù)!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResLoginEnvelope> call, Throwable t) {
Toast.makeText(getApplicationContext(), "請求失敗,網(wǎng)絡(luò)超時!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mCall.isExecuted()) {
mCall.cancel();
}
}
}
四、總結(jié)
上面為除布局文件外的全部的代碼,簡化了很多內(nèi)容。其實解決解析 SOAP XML 數(shù)據(jù)的過程還是有點意思的。從一開始 Google 不到相關(guān)信息到解決,其中還是有很多小坑的。不過過程是坎坷的結(jié)果是美好的。
PS:有意見請留言!
2018/9/21 17:37:51
