Android使用Retrofit请求WebService

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Greathfs/article/details/71338055

1.配置app build.gradle

 /**
     * network
     */
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile('com.squareup.retrofit2:converter-simplexml:2.0.2') {
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
        exclude group: 'xpp3', module: 'xpp3'
    }
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

2.配置Okhttp和Retrofit

    /**
     * 配置Okhttp
     */
    public void configGoodsOkhttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.i("RetrofitLog", "retrofitBack = " + message);
                }
            });
            /**
             * 设置Log打印级别 类型为BASIC,其实日志级别分为4类:NONE、BASIC、HEADERS、BODY
             *
             * NONE:没有任何log BASIC:请求/响应行 HEADERS:请求/响应行 + 头 BODY:请求/响应行 + 头 + 体
             */
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        builder.interceptors().add(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request original = chain.request();

                Request.Builder requestBuilder = original.newBuilder()
                        .header("Content-Type", "text/xml;charset=UTF-8")   // 对于SOAP 1.1, 如果是soap1.2 应是Content-Type: application/soap+xml; charset=utf-8
                        .method(original.method(), original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

        /**
         * 设置超时
         */
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        /**
         * 错误重连
         */
        builder.retryOnConnectionFailure(true);
        mGoodHttpClient = builder.build();
    }

3.获取到对应的Service

  /**
     * 获取Goodervice
     *
     * @return
     */
    private GoodService getGoodService() {
        Retrofit goodRetrofit = new Retrofit.Builder().baseUrl(Constants.HOST).client(mGoodHttpClient)
                .addConverterFactory(SimpleXmlConverterFactory.create()).build();
        return goodRetrofit.create(GoodService.class);
    }

4.创建对应Service

public interface GoodService {

   @POST("services/salesBillService?wsdl")
    Call<GoodResponseEnvelope> getRoleInfo(@Body GoodRequestEnvelope requestEnvelope);
}

5.SoapUi界面

request:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cxf="http://cxf.web.openplatform.wz.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <cxf:findWithPage>
         <!--Optional:-->
         <arg0>0</arg0>
         <arg1>1</arg1>
         <arg2>10</arg2>
         <!--Optional:-->
         <arg3>10043615</arg3>
      </cxf:findWithPage>
   </soapenv:Body>
</soapenv:Envelope>

response:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:findWithPageResponse xmlns:ns2="http://cxf.web.openplatform.wz.com/">
         <return>{"total":8,"goodsList":[{"bg_tid":9,"bg_jobcode":null,"bg_name":"11","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":1.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":1.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":1.0,"bg_maker":null,"bg_brand":null,"bg_code":"114","bg_classnum":"","bg_class":"666","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487871902,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"11","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":10,"bg_jobcode":null,"bg_name":"11","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":1.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":1.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":1.0,"bg_maker":null,"bg_brand":null,"bg_code":"115","bg_classnum":"","bg_class":"666","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487871903,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"11","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":11,"bg_jobcode":null,"bg_name":"11","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":3.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":3.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":3.0,"bg_maker":null,"bg_brand":null,"bg_code":"11","bg_classnum":"","bg_class":"999","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487874460,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"11","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":12,"bg_jobcode":null,"bg_name":"11","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":3.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":3.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":3.0,"bg_maker":null,"bg_brand":null,"bg_code":"22","bg_classnum":"","bg_class":"999","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487874460,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"11","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":13,"bg_jobcode":null,"bg_name":"33","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":3.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":3.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":3.0,"bg_maker":null,"bg_brand":null,"bg_code":"33","bg_classnum":"","bg_class":"999","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487874460,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"33","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":14,"bg_jobcode":null,"bg_name":"11","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":1.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":1.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":1.0,"bg_maker":null,"bg_brand":null,"bg_code":"116","bg_classnum":"","bg_class":"666","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1487871903,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"11","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":71,"bg_jobcode":null,"bg_name":"111","bg_spec":"111","bg_unit":null,"bg_smgetprice":11.0,"bgp_Zprices":22.0,"bgp_Zhuiyuan":11.0,"bgp_Xprices":22.0,"bgp_Xhuiyuan":11.0,"bg_favprice":0.0,"bm_XPrices":22.0,"bg_maker":null,"bg_brand":null,"bg_code":"1234","bg_classnum":"","bg_class":"999","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1488126843,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"111","bg_ifWholesale":null,"bg_wholesalePrice":11.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null},{"bg_tid":72,"bg_jobcode":null,"bg_name":"114232424242424242424","bg_spec":"11","bg_unit":null,"bg_smgetprice":1.0,"bgp_Zprices":5.0,"bgp_Zhuiyuan":1.0,"bgp_Xprices":5.0,"bgp_Xhuiyuan":1.0,"bg_favprice":0.0,"bm_XPrices":5.0,"bg_maker":null,"bg_brand":null,"bg_code":"112","bg_classnum":"","bg_class":"999","bg_area_num":"","bg_isbub":true,"bg_recnum":0,"bg_bubgetprice_notax":0.0,"sg_coupprice":0,"bg_provider_num":null,"bg_Day":0,"bg_Num":0,"bg_isTeJia":null,"bg_limitDays":null,"bg_limitNum":null,"bg_goodsCoupprice":0.0,"is_weight":null,"bg_stamp":1488129779,"bg_activeFlag":"1","bg_imgUrl":"","bg_letterShort":"114232424242424242424","bg_ifWholesale":null,"bg_wholesalePrice":1.0,"bg_minimumPurchase":null,"cheapDate":null,"payType":null}]}</return>
      </ns2:findWithPageResponse>
   </soap:Body>
</soap:Envelope>

6.写请求类

@Root(name = "soapenv:Body", strict = false)
public class GoodRequestBody {

    @Element(name = "cxf:findWithPage", required = false)
    private GoodRequestData goodRequestData;

    public GoodRequestData getGoodRequestData() {
        return goodRequestData;
    }

    public void setGoodRequestData(GoodRequestData goodRequestData) {
        this.goodRequestData = goodRequestData;
    }
}
public class GoodRequestData {

    @Element(name = "arg0")
    private String arg0;

    @Element(name = "arg1")
    private int arg1;

    @Element(name = "arg2")
    private int arg2;

    @Element(name = "arg3")
    private String arg3;

    public String getArg0() {
        return arg0;
    }

    public void setArg0(String arg0) {
        this.arg0 = arg0;
    }

    public int getArg1() {
        return arg1;
    }

    public void setArg1(int arg1) {
        this.arg1 = arg1;
    }

    public int getArg2() {
        return arg2;
    }

    public void setArg2(int arg2) {
        this.arg2 = arg2;
    }

    public String getArg3() {
        return arg3;
    }

    public void setArg3(String arg3) {
        this.arg3 = arg3;
    }
}
@Root(name = "soapenv:Envelope")
@NamespaceList({
        @Namespace(reference = "http://cxf.web.openplatform.wz.com/", prefix = "cxf"),
        @Namespace(reference = "http://schemas.xmlsoap.org/soap/envelope/", prefix = "soapenv")
})
public class GoodRequestEnvelope {


    @Element(name = "soapenv:Body", required = false)
    private GoodRequestBody body;

    @Element(name = "soapenv:Header", required = false)
    public String header;

    public GoodRequestBody getBody() {
        return body;
    }

    public void setBody(GoodRequestBody body) {
        this.body = body;
    }
}

7.写响应类

@Root(name = "soap:Body", strict = false)
@NamespaceList({
        @Namespace(reference = "http://cxf.web.openplatform.wz.com/", prefix = "ns2")
})
public class GoodResponseBody {

    @Element(name = "findWithPageResponse", required = false)
    private GoodResponseData data;

    public GoodResponseData getData() {
        return data;
    }

    public void setData(GoodResponseData data) {
        this.data = data;
    }
}
@Root(name = "ns2:findWithPageResponse", strict = false)
public class GoodResponseData {

    @Element(name = "return")
    private String result;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}

@Root(name = "soap:Envelope")
@NamespaceList({
        @Namespace(reference = "http://schemas.xmlsoap.org/soap/envelope/", prefix = "soap")
})
public class GoodResponseEnvelope {

    @Element(required = false, name = "Body")
    private GoodResponseBody body;

    public GoodResponseBody getBody() {
        return body;
    }

    public void setBody(GoodResponseBody body) {
        this.body = body;
    }
}

8.写网络请求

    /**
     * 下载商品
     */
    private void downloadGoods() {
        GoodRequestEnvelope goodRequestEnvelope = new GoodRequestEnvelope();
        GoodRequestBody goodRequestBody = new GoodRequestBody();

        GoodRequestData goodRequestData = new GoodRequestData();
        goodRequestData.setArg0("0");
        goodRequestData.setArg1(1);
        goodRequestData.setArg2(1);
        goodRequestData.setArg3("10033481");
        goodRequestBody.setGoodRequestData(goodRequestData);

        goodRequestEnvelope.setBody(goodRequestBody);

        Call<GoodResponseEnvelope> goodResponseEnvelopeCall = RetrofitUtil.getInstance().downloadGoods(goodRequestEnvelope);
        goodResponseEnvelopeCall.enqueue(new Callback<GoodResponseEnvelope>() {
            @Override
            public void onResponse(Call<GoodResponseEnvelope> call, Response<GoodResponseEnvelope> response) {
                if (response != null && response.isSuccessful()) {
                    GoodResponseEnvelope goodResponseEnvelope = response.body();
                    if (goodResponseEnvelope != null) {
                        String mg = goodResponseEnvelope.getBody().getData().getResult();
                    }
                }
            }

            @Override
            public void onFailure(Call<GoodResponseEnvelope> call, Throwable t) {
                showToast(t.getMessage());
            }
        });
    }
 /**
     * 下载商品
     *
     * @param goodRequestEnvelope 请求Request
     */
    public Call<GoodResponseEnvelope> downloadGoods(GoodRequestEnvelope goodRequestEnvelope) {
        return mGoodService.getRoleInfo(goodRequestEnvelope);
    }
public class RetrofitUtil {

    private static RetrofitHelper mRetrofitHelper = null;

    public static void initRetrogitHelp() {
        mRetrofitHelper = new RetrofitHelper();
    }

    /**
     * 单例模式获取RetrifitHelp
     * @return
     */
    public static RetrofitHelper getInstance() {
        if (mRetrofitHelper == null) {
            mRetrofitHelper = new RetrofitHelper();
        }
        return mRetrofitHelper;
    }

}

猜你喜欢

转载自blog.csdn.net/Greathfs/article/details/71338055