SOAP-WebService 用Retrofit2请求

零、概述

项目由于种种原因导致后台服务是用 C# 编写。请求与返回的数据格式是 SOAP 型的 XML 。外加上国内外对此描述的文章非常稀少,所以才有了此篇小作文儿。

一、相关需求

  1. 解决 SOAP 1.1 或 SOAP 1.2 的 WebService 与 Android 通讯问题。
  2. 请求、响应数据格式如下图


    image

二、选择方案

  1. 最终选择使用 SOAP 1.1 用来通讯。 SOAP 1.2 个人未做测试不过感觉原理差不多。
  2. 使用 simplexml 搭配 Retrofit2 进行 XML 解析。

三、干货

1.目录结构

image

PS:原本想把响应参数也抽调成共通 Base 结果发现抽调后不能正常解析。

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:由于早期开发 Java 后台习惯用 FastJson 来解析 Json ,所以使用了 FastJson 。

3.网络模块

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:前些日子看到用枚举特性来实现单例,这里用用。

RetrofitManage
/**
 * @Description Retrofit2.0 管理类
 */
public class RetrofitManage {

    /**
     * HTTP 请求地址
     **/
    private final String API_URL = "http://192.168.1.200:200";

    /**
     * 网络请求api
     */
    private RetrofitService api;

    /**
     * 构造方法
     */
    public RetrofitManage() {
        // OkHttp3 配置
        OkHttpClient client = new OkHttpClient.Builder()
                // 连接超时时间
                .connectTimeout(7676, TimeUnit.SECONDS)
                // 读取时间
                .readTimeout(7676, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                // 服务器请求URL
                .baseUrl(API_URL)
                // 转换器方式为XML
                .addConverterFactory(SimpleXmlConverterFactory.create())
                // OkHttp3 对象
                .client(client)
                .build();

        // 获取Proxy.newProxyInstance动态代理对象
        api = retrofit.create(RetrofitService.class);
    }

    /**
     * 外部获取 RetrofitService
     * @return ZLRetrofitService
     */
    public RetrofitService getApi() {
        return api;
    }
}

PS:addConverterFactory 这里使用 SimpleXmlConverterFactory 来转换。注意 XML 转换方式与Json转换方式不能同时使用。如果同时加入则先加入的生效。还是来个例子说明一下吧。
EG:下例 Gson 转换生效 XML 不能生效。

Retrofit retrofit = new Retrofit.Builder()
        // 服务器请求URL
        .baseUrl(API_URL)
        // 添加Gson转换器 需添加依赖 'com.squareup.retrofit2:converter-gson:2.1.0'
        .addConverterFactory(GsonConverterFactory.create())
        // 转换器方式为XML
        .addConverterFactory(SimpleXmlConverterFactory.create())
        // OkHttp3 对象
        .client(client)
        .build();
RetrofitService
/**
 * @Description Retrofit 2.0 网络请求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.业务模块

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 响应登录 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 响应登录 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 响应登录 返回值
 */
@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;

    // 网络请求API
    private RetrofitService mApi;
    // 接口回调
    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(), "未请求到数据!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResLoginEnvelope> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "请求失败,网络超时!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCall.isExecuted()) {
            mCall.cancel();
        }
    }
}

四、总结

上面为除布局文件外的全部的代码,简化了很多内容。其实解决解析 SOAP XML 数据的过程还是有点意思的。从一开始 Google 不到相关信息到解决,其中还是有很多小坑的。不过过程是坎坷的结果是美好的。
PS:有意见请留言!


2018/9/21 17:37:51

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,099评论 1 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,097评论 18 139
  • 1. XML简介 以下内容来自于http://www.w3school.com.cn/xml 基本知识 XML 和...
    WebSSO阅读 1,713评论 1 7
  • 1 我正在洗衣房洗衣服,小麦惊慌失措跑过来:妈,不得了啦,小树拉屎啦,她没有打尿包,都拉到地上啦!她拉了三段屎! ...
    应童阅读 3,603评论 14 44
  • 有一种念想,每每孤思就潸然泪下。 太概是过多的寄托, 又不能相触及吧。 因为相应,因此相念。 幽深古道,只身入野,...
    大象姐说心理阅读 222评论 0 0