天天看點

Android開發調用webservice接口

直接上代碼:

public class HttpUtil {
    //wsdl的uri
    private static final String URL = "http://x.x.x.x:x/Service/AppService.asmx?WSDL";

    public static <T>  void baseJSONObject(final Observer<JSONObject> observer, final SoapObject request){
        Observable<T> oble = Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<T> e) throws Exception {
                String response = post(request);
                if(response != null){
                    System.out.println("baseJSONObject:" + response);
                    e.onNext((T) JSON.parseObject(response));
                    e.onComplete();
                }else{
                    e.onError(new IOException());
                }
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());
        Observer oser = observer;
        oble.subscribe(oser);
    }

    //調用webservice
    public static String post(SoapObject request) {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER12);
        envelope.bodyOut = request;
        envelope.dotNet = true;
        HttpTransportSE httpTransportSE = new HttpTransportSE(URL);
        try {
            httpTransportSE.call(null, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SoapObject object = (SoapObject) envelope.bodyIn;
        String result =  object.getProperty(0).toString();
        return result;
    }
}
           

我這裡是定義了一個 HttpUtil 類,其中的 x.x.x.x:x就是你需要調用的ip位址和端口号了。

然後在你的自己定義的接口檔案中定義你要調用的接口和參數,形式如下:

public static void function(Observer<JSONObject> observer, Type param, ...) {
     SoapObject request = new SoapObject(NAMESPACE, "func");
     request.addProperty("param", param); //傳入參數,無參可省略這一步
     baseJSONObject(observer, request);
}
           

其中的 NAMESPACE是我定義的一個類屬性常量,在浏覽器中輸入

http://x.x.x.x:x/Service/AppService.asmx?WSDL
           

就會出現如下頁面

<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema"
				xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
				xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
				xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
				xmlns:tns="http://tempuri.org/"
				xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
				xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
				xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
				xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
				targetNamespace="http://tempuri.org/">
...
           

倒數第二行的 targetNamespace 字段的值就是命名空間,而 func 就是你要真正調用的接口名啦!