retrofit2調(diào)用webservice請求一共3篇
一:工具
二:通過retrofit2 進行soap請求
三:攔截器,通過retrofit2 攔截器拼接入?yún)⒑瓦^濾出返回值壹甥,使soap請求更趨向于http請求
1.使用的是公共的測試接口:獲取天氣的http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
原理很簡單救巷,其實就是通過把入?yún)⑵唇悠饋恚缓蟀裺oap的請求轉(zhuǎn)變?yōu)閔ttp的post請求的方式句柠,來實現(xiàn)用retrofit2來調(diào)用soap接口請求征绸。
getSupportCity接口入?yún)ⅲ?/p>
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>
看到這個,先擼一個拼接入?yún)ML的幫助類:
import android.util.Log;
import java.util.Map;
/**
* Created by Frank on 2016/12/9.
* 拼接http請求的頭文件
*/
public class ApiNode {
// 轉(zhuǎn)義字符-> <xxx>
public static String toStart2(String name) {
return "<" + name + ">";
}
// 轉(zhuǎn)義字符-> </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+"請求入?yún)?" + 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 {
// 超時時間 默認(rèn)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)// 服務(wù)地址:"http://www.webxml.com.cn/WebServices/"
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
apiStores = mRetrofit.create(ApiStores.class);
}
//在訪問HttpMethods時創(chuàng)建單例
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);
}
}
這里是簡單的寫俄占,所以調(diào)用接口的那一層寫在了AppClient類里面,正常應(yīng)該要再分一層的
最后是retrofit的接口層
import okhttp3.ResponseBody;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import rx.Observable;
/**
* Created by Frank on 2016/12/9.
* 網(wǎng)絡(luò)請求地址,舊的模式(請求沒有用攔截器)
*/
public interface ApiStores {
// 通過省份獲取城市代碼,頭文件在第一篇都有講到
@Headers({
"Content-Type:text/xml; charset=utf-8",
"SOAPAction:http://WebXml.com.cn/getSupportCity"
})
// 這里對應(yīng) 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去調(diào)用-->方法如下:
/**
* 通過省份獲取城市代碼,無封裝
*/
public void getSupportCityByFirst() {
// 拼接入?yún)? Map map = new HashMap<>();
map.put("byProvinceName", "福建");
String result = ApiNode.getParameter("getSupportCity", map);
// 調(diào)用
AppClient.getInstance().getSupportCity(result)
.subscribeOn(Schedulers.io())// 指定 subscribe() 發(fā)生在 IO 線程
.observeOn(AndroidSchedulers.mainThread())// 指定 Subscriber 的回調(diào)發(fā)生在主線程
.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();
}
}
});
}
最后打印出來的入?yún)ⅲ?/p>
<?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>