使用android-async-http发送soap异步请求

阅读更多
android-async-http是处理http处理的开源网络框架。
地址如下:
https://github.com/loopj/android-async-http

选择android-async-http库来处理android网络通信处理,完全是因为呼声够高。期间在研究该库soap通信时,发现了关于该库做soap通信时的讨论帖,在网上资料很少的情况下,看到这个讨论也算是很好的教材。
https://github.com/loopj/android-async-http/issues/403

下来开始本地测试。

1.在本地搭建WebService服务,搭建方法: http://xushans.iteye.com/blog/2218801
WebService具体功能类:
package com.test;

public class Axis2WB {

    /**
     * 提供了一个说Hello的服务
     * 
     * @return
     */
    public String sayHello( String name ) {
        return "Hello " + name;
    }

    /**
     * 提供了一个做加法的服务
     * 
     * @param a
     * @param b
     * @return
     */
    public int add( int a, int b ) {
        return a + b;
    }
}


2.打包启动后,生成的wsdl:
This XML file does not appear to have any style information associated with it. The document tree is shown below.

Axis2WB




































































































































3.使用SoapUI生成soap request:
http://xushans.iteye.com/blog/2220718

4.利用android-async-http编写代码:
String xmlRequest = ""
        + ""
        + "" + "" + "" + "liu"
        + "" + "" + "";

String contentType = "text/xml;charset=utf-8";
StringEntity entity = null;

try {
    entity = new StringEntity( xmlRequest, "UTF-8" );
} catch ( UnsupportedEncodingException e ) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

entity.setContentType( contentType );
entity.setContentEncoding( new BasicHeader( HTTP.CONTENT_ENCODING, contentType ) );

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader( "Content-Type", contentType );
client.addHeader( "SOAPAction", "http://test.com/:sayHello" );

client.post( context, "http://xxx.xxx.xxx.xxx:8080/axis2/services/Axis2WB?wsdl", entity, contentType,
        new AsyncHttpResponseHandler() {

            @Override
            public void onFailure( int arg0, Header[] arg1, byte[] arg2, Throwable arg3 ) {
                // TODO Auto-generated method stub
                String result = arg2.toString();
                System.out.println( result );
            }

            @Override
            public void onSuccess( int arg0, Header[] arg1, byte[] arg2 ) {
                // TODO Auto-generated method stub

                String result = new String( arg2 );
                System.out.println( result );
            }
        } );


其中,在xmlRequest中,设置需要调用webService的方法sayHello的参数 liu。创建异步通信对象AsyncHttpClient时,设置header属性 Content-Typetext/xml;charset=utf-8,设置header属性 SOAPActionhttp://test.com/:sayHello(http://test.com是命名空间,sayHello是方法名)。设置AsyncHttpClient.post方法的url参数为 webService的wsdl的url。设置response控制类为异步类AsyncHttpResponseHandler。

测试结果,收到soap response:
Hello liu

你可能感兴趣的:(soap,webservice)