retrofit2调用webservice请求一共3篇
一:工具
二:通过retrofit2 进行soap请求
三:拦截器,通过retrofit2 拦截器拼接入参和过滤出返回值,使soap请求更趋向于http请求
1.使用的是公共的测试接口:获取天气的http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
原理很简单,其实就是通过把入参拼接起来,然后把soap的请求转变为http的post请求的方式,来实现用retrofit2来调用soap接口请求。
getSupportCity接口入参:
POST /WebServices/WeatherWebService.asmx HTTP/1.1
Host: www.webxml.com.cn
Content-Type: text/xml; charset=utf-8 // headers头信息
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getSupportCity" // headers头信息
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getSupportCity xmlns="http://WebXml.com.cn/">
<byProvinceName>string</byProvinceName>
</getSupportCity>
</soap:Body>
</soap:Envelope>
看到这个,先撸一个拼接入参XML的帮助类:
import android.util.Log;
import java.util.Map;
/**
* Created by Frank on 2016/12/9.
* 拼接http请求的头文件
*/
public class ApiNode {
// 转义字符-> <xxx>
public static String toStart2(String name) {
return "<" + name + ">";
}
// 转义字符-> </xxx>
public static String toEnd2(String name) {
return "</" + name + ">";
}
// 正常字符-> <xxx>
public static String toStart(String name) {
return "<" + name + ">";
}
// 正常字符-> </xxx>
public static String toEnd(String name) {
return "</" + name + ">";
}
public static String getParameter(String namespace, Map<String, String> map) {
StringBuffer sbf = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
sbf.append(ApiNode.toStart(entry.getKey()));
sbf.append(entry.getValue());
sbf.append(ApiNode.toEnd(entry.getKey()));
}
String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
" <soap:Body>" +
" <" + namespace + " xmlns=\"http://WebXml.com.cn/\">" + sbf.toString() +
" </" + namespace + ">" +
" </soap:Body>" +
"</soap:Envelope>";
Log.v("test", namespace+"请求入参:" + str);
return str;
}
}
先写个简单的Retrofit初始化工具
import java.util.concurrent.TimeUnit;
import linc.ps.net_common.BuildConfig;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
/**
* Created by Frank on 2016/12/11.
* Retrofit初始化工具,旧的模式(请求没有用拦截器)
*/
public class AppClient {
// 超时时间 默认5秒
private static final int DEFAULT_TIMEOUT = 20;
public static Retrofit mRetrofit;
private ApiStores apiStores;
private AppClient() {
if (mRetrofit == null) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true); //连接失败后是否重新连接
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
OkHttpClient okHttpClient = builder.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.API_SERVER_URL)// 服务地址:"http://www.webxml.com.cn/WebServices/"
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
apiStores = mRetrofit.create(ApiStores.class);
}
//在访问HttpMethods时创建单例
private static class SingletonHolder{
private static final AppClient INSTANCE = new AppClient();
}
//获取单例
public static AppClient getInstance(){
return SingletonHolder.INSTANCE;
}
public Observable<ResponseBody> getSupportCity(String string) {
return apiStores.getSupportCity(string);
}
}
这里是简单的写,所以调用接口的那一层写在了AppClient类里面,正常应该要再分一层的
最后是retrofit的接口层
import okhttp3.ResponseBody;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import rx.Observable;
/**
* Created by Frank on 2016/12/9.
* 网络请求地址,旧的模式(请求没有用拦截器)
*/
public interface ApiStores {
// 通过省份获取城市代码,头文件在第一篇都有讲到
@Headers({
"Content-Type:text/xml; charset=utf-8",
"SOAPAction:http://WebXml.com.cn/getSupportCity"
})
// 这里对应 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName 里面的WeatherWebService
@POST("WeatherWebService.asmx")
Observable<ResponseBody> getSupportCity(@retrofit2.http.Body String s);
}
这里要注意的是 @Headers里面的http://WebXml.com.cn/getSupportCity 里的 getSupportCity 每个方法是不一样的,而且每个方法必须写一次,有点麻烦,下一章会讲到拦截器的方式。
写个button去调用-->方法如下:
/**
* 通过省份获取城市代码,无封装
*/
public void getSupportCityByFirst() {
// 拼接入参
Map map = new HashMap<>();
map.put("byProvinceName", "福建");
String result = ApiNode.getParameter("getSupportCity", map);
// 调用
AppClient.getInstance().getSupportCity(result)
.subscribeOn(Schedulers.io())// 指定 subscribe() 发生在 IO 线程
.observeOn(AndroidSchedulers.mainThread())// 指定 Subscriber 的回调发生在主线程
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
Log.e("test", "---getSupportCityByFirst onCompleted--->");
}
@Override
public void onError(Throwable e) {
Log.e("test", "---getSupportCityByFirst onError--->");
}
@Override
public void onNext(ResponseBody response) {
try {
String res = response.string();
Log.e("test", "---getSupportCityByFirst onNext str--->"+res);
} catch (IOException e) {
Log.e("test", "---getSupportCityByFirst onNext str-IOException-->"+e.getMessage());
e.printStackTrace();
}
}
});
}
最后打印出来的入参:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getSupportCity xmlns="http://WebXml.com.cn/">
<byProvinceName>福建</byProvinceName>
</getSupportCity>
</soap:Body>
</soap:Envelope>
最后打印出来的返回值:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getSupportCityResponse xmlns="http://WebXml.com.cn/"> <getSupportCityResult>
<string>福州 (58847)</string><string>厦门 (59134)</string><string>龙岩 (58927)</string><string>南平 (58834)</string><string>宁德 (58846)</string><string>莆田 (58946)</string><string>泉州 (59137)</string><string>三明 (58828)</string><string>漳州 (59126)</string>
</getSupportCityResult>
</getSupportCityResponse>
</soap:Body>
</soap:Envelope>