java - test - wsdl soap




如何在Android上調用SOAP Web服務 (18)

不要忘記在您的項目中添加ksoap2.jar,並在AndroidManifest文件中添加INTERNET權限

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WebserviceActivity extends Activity {

    private static final String NAMESPACE = "https://api.authorize.net/soap/v1/";
    private static final String URL ="https://apitest.authorize.net/soap/v1/Service.asmx?wsdl"; 
    private static final String SOAP_ACTION = "https://api.authorize.net/soap/v1/AuthenticateTest";
    private static final String METHOD_NAME = "AuthenticateTest";
    private TextView lblResult;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lblResult = (TextView) findViewById(R.id.tv);

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        request.addProperty("name","44vmMAYrhjfhj66fhJN");
        request.addProperty("transactionKey","9MDQ7fghjghjh53H48k7e7n");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);

            //SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            // SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;


            lblResult.setText(resultsRequestSOAP.toString());
            System.out.println("Response::"+resultsRequestSOAP.toString());


        } catch (Exception e) {
            System.out.println("Error"+e);
        }

    }
}

我很難找到有關如何使用Android調用標準SOAP / WSDL Web服務的良好信息。 我所能找到的都是非常複雜的文檔和對“kSoap2”的引用,然後關於用SAX手動解析它的一些內容。 好吧,沒關係,但是它是2008年的,所以我認為應該有一些用於調用標準Web服務的好庫。

Web服務基本上是在NetBeans創建的。 我希望IDE支持生成管道類。 我只需要以最簡單/最優雅的方式聯繫基於Android的手機的基於WSDL的Web服務。


Android不提供任何類型的SOAP庫。 你可以自己寫,也可以使用kSOAP 2之類的東西。 正如你注意到的,其他人已經能夠在他們自己的項目中編譯和使用kSOAP2,但我不必這樣做。

到目前為止,Google已經向Android添加SOAP庫的興趣不大。 我懷疑這是因為他們寧願支持Web服務當前趨向於基於REST的服務,並將JSON用作數據封裝格式。 或者,使用XMPP進行消息傳遞。 但這只是猜測。

目前,基於XML的Web服務在Android上是一項稍微不重要的任務。 不知道NetBeans,我不能說說那裡的工具,但我同意應該有一個更好的庫。 XmlPullParser可能會讓你免於使用SAX,但我對此不太了解。



大約一年前,我正在閱讀本主題,試圖弄清楚如何在Android上進行SOAP調用 - 使用HttpClient構建自己的建議導致我為Android構建自己的SOAP庫:

IceSoap

基本上它允許你通過一個簡單的Java API建立信封發送,然後自動將它們解析成你通過XPath定義的對象......例如:

<Dictionary>
    <Id></Id>
    <Name></Name>
</Dictionary>

變為:

@XMLObject("//Dictionary")
public class Dictionary {
    @XMLField("Id")
    private String id;

    @XMLField("Name")
    private String name;
}

我將它用於自己的項目,但我認為它可以幫助其他人,所以我花了一些時間將它分離出來並記錄下來。 我真的很喜歡它,如果你的一些可憐的靈魂在谷歌搜索“SOAP Android”的時候偶然發現,它可能會給它帶來一些好處。



如果您在android中調用Web服務時遇到問題,那麼您可以使用以下代碼調用Web服務並獲取響應。確保您的Web服務以數據表格式返迴響應。如果您使用的數據來自SQL Server數據庫。如果您使用MYSQL ,則需要更改一件事,只需從句子obj2=(SoapObject) obj1.getProperty("NewDataSet");替換單詞NewDataSet obj2=(SoapObject) obj1.getProperty("NewDataSet");DocumentElement提供

void callWebService(){

private static final String NAMESPACE = "http://tempuri.org/"; // for wsdl it may be package name i.e http://package_name
private static final String URL = "http://localhost/sample/services/MyService?wsdl";
// you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = "urn:" + METHOD_NAME;

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("parm_name", prm_value);// Parameter for Method
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;// **If your Webservice in .net otherwise remove it**
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);// call the eb service
                                                                                                         // Method
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Next task is to get Response and format that response
    SoapObject obj, obj1, obj2, obj3;
    obj = (SoapObject) envelope.getResponse();
    obj1 = (SoapObject) obj.getProperty("diffgram");
    obj2 = (SoapObject) obj1.getProperty("NewDataSet");

    for (int i = 0; i < obj2.getPropertyCount(); i++) { 
// the method getPropertyCount() and  return the number of rows
            obj3 = (SoapObject) obj2.getProperty(i);
            obj3.getProperty(0).toString();// value of column 1
            obj3.getProperty(1).toString();// value of column 2
            // like that you will get value from each column
        }
    }

如果您對此有任何疑問,請寫信給我..


幾個月前,我在j2ee應用程序中使用jax-ws web服務,在那裡我們使用CXF wsdl2java從WSDL文件生成WS客戶端存根,並使用這些客戶端存根來使用Web服務。 幾個星期前,當我試圖在Android平台上以相同的方式使用Web服務時,我無法使用Web服務,因為Android jar並不是所有支持其中的類的“jax-ws”。 那次我沒有找到任何這樣的工具(如果我沒有失敗谷歌效率),以滿足我的要求 -

  • 從WSDL獲取客戶端存根。
  • 並用一些參數(java業務請求對象)調用服務。
  • 獲取響應業務對象。

所以,我開發了我自己的Android SOAP客戶端生成工具 。 你必須遵循以下步驟:

  • 從WSDL獲取WS客戶端存根,將其放入您的項目中。
  • 對某些服務說“ComplexOperationService”,實例化服務,獲取端點端口並調用服務方法,並從Web服務獲取響應:

例如:

ComplexOperationService service = new ComplexOperationService( );
ComplexOperation port= service.getComplexOperationPort();    
SomeComplexRequest request = --Get some complex request----;    
SomeComplexResp resp = port.operate( request  );
  • 您不需要關心服務類/ req / response類或任何其他類和方法,因為您知道它們都是從WSDL生成的。
  • 當然,你不需要知道soap action / envelop / namespace等。只需要像開發者一樣調用方法。

您可以使用某些標題以http的形式執行soap調用。 我解決了這個問題,沒有像ksoap2這樣的附加庫這裡是從soap服務獲取訂單的實時代碼

private static HashMap<String,String> mHeaders = new HashMap<>();

static {
    mHeaders.put("Accept-Encoding","gzip,deflate");
    mHeaders.put("Content-Type", "application/soap+xml");
    mHeaders.put("Host", "35.15.85.55:8080");
    mHeaders.put("Connection", "Keep-Alive");
    mHeaders.put("User-Agent","AndroidApp");
    mHeaders.put("Authorization","Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
}public final static InputStream receiveCurrentShipments(String stringUrlShipments)
{
    int status=0;
    String xmlstring= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ser=\"http://35.15.85.55:8080/ServiceTransfer\">\n" +
            "   <soap:Header/>\n" +
            "   <soap:Body>\n" +
            "      <ser:GetAllOrdersOfShipment>\n" +
            "         <ser:CodeOfBranch></ser:CodeOfBranch>\n" +
            "      </ser:GetAllOrdersOfShipment>\n" +
            "   </soap:Body>\n" +
            "</soap:Envelope>";
    StringBuffer chaine = new StringBuffer("");

    HttpURLConnection connection = null;
    try {
        URL url = new URL(stringUrlShipments);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Length", xmlstring.getBytes().length + "");
        connection.setRequestProperty("SOAPAction", "http://35.15.85.55:8080/ServiceTransfer/GetAllOrdersOfShipment");

        for(Map.Entry<String, String> entry : mHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            connection.setRequestProperty(key,value);

        }

        connection.setRequestMethod("POST");
        connection.setDoInput(true);

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(xmlstring.getBytes("UTF-8"));
        outputStream.close();

        connection.connect();
        status = connection.getResponseCode();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        Log.i("HTTP Client", "HTTP status code : " + status);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return inputStream;
}


我會建議查看一個非常有用的工具,這對我有很大的幫助。 照顧這個項目的人也非常有幫助。 www.wsdl2code.com/




添加Soap Libaray( ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar ):

public static String Fn_Confirm_CollectMoney_Approval(

        HashMap < String, String > str1,
        HashMap < String, String > str2,
        HashMap < String, String > str3) {

    Object response = null;
    String METHOD_NAME = "CollectMoney";
    String NAMESPACE = "http://xxx/yyy/xxx";
    String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    String SOAP_ACTION = "";

    try {

        SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapObject Request1 = new SoapObject(NAMESPACE, "req");

        PropertyInfo pi = new PropertyInfo();

        Set mapSet1 = (Set) str1.entrySet();

        Iterator mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            String keyValue = (String) mapEntry.getKey();

            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        mapSet1 = (Set) str3.entrySet();

        mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        SoapObject HeaderRequest = new SoapObject(NAMESPACE, "XXX");

        Set mapSet = (Set) str2.entrySet();

        Iterator mapIterator = mapSet.iterator();

        while (mapIterator.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            HeaderRequest.addProperty(pi);
        }

        Request1.addSoapObject(HeaderRequest);

        RequestParent.addSoapObject(Request1);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);

        soapEnvelope.dotNet = false;

        soapEnvelope.setOutputSoapObject(RequestParent);

        HttpTransportSE transport = new HttpTransportSE(URL, 120000);

        transport.debug = true;

        transport.call(SOAP_ACTION, soapEnvelope);

        response = (Object) soapEnvelope.getResponse();

        int cols = ((SoapObject) response).getPropertyCount();

        Object objectResponse = (Object) ((SoapObject) response)
                .getProperty("Resp");

        SoapObject subObject_Resp = (SoapObject) objectResponse;


        modelObject = new ResposeXmlModel();

        String MsgId = subObject_Resp.getProperty("MsgId").toString();


        modelObject.setMsgId(MsgId);

        String OrgId = subObject_Resp.getProperty("OrgId").toString();


        modelObject.setOrgId(OrgId);

        String ResCode = subObject_Resp.getProperty("ResCode").toString();


        modelObject.setResCode(ResCode);

        String ResDesc = subObject_Resp.getProperty("ResDesc").toString();


        modelObject.setResDesc(ResDesc);

        String TimeStamp = subObject_Resp.getProperty("TimeStamp")
                .toString();


        modelObject.setTimestamp(ResDesc);

        return response.toString();

    } catch (Exception ex) {

        ex.printStackTrace();

        return null;
    }

}

由於需要處理/解析開銷,SOAP在Android(或通常的移動設備)上使用時不適用。 REST服務是一個更輕的解決方案,這就是我的建議。 Android帶有一個SAX解析器,使用起來相當簡單。 如果您絕對需要在移動設備上處理/解析SOAP,那麼我為您感到難過,我所能提供的最佳建議就是不使用SOAP。


要從android調用SOAP Web Service,請嘗試使用此客戶端

不要忘記在你的java構建路徑中添加ksoap2-android.jar

public class WsClient {
    private static final String SOAP_ACTION = "somme";
    private static final String OPERATION_NAME = "somme";
    private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
    private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";

    public String caclculerSomme() {

        String res = null;
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                OPERATION_NAME);
        request.addProperty("a", "5");
        request.addProperty("b", "2");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

        try {
            httpTransport.call(SOAP_ACTION, envelope);
            String result = envelope.getResponse().toString();
            res = result;
            System.out.println("############# resull is :" + result);
        } catch (Exception exception) {
            System.out.println("########### ERRER" + exception.getMessage());
        }

        return res;
    }
}

要從移動設備(特別是在Android手機上)調用Web服務,我已經使用了一種非常簡單的方法來完成它。 我尚未使用任何Web服務客戶端API嘗試調用Web服務。 我的方法如下撥打電話。

  1. 使用Java標準API HttpURLConnection創建一個簡單的HTTP連接。
  2. 形成一個SOAP請求。 (您可以幫助SOAPUI進行SOAP請求。)
  3. 將doOutPut標誌設置為true。
  4. 設置HTTP標頭值,如內容長度,內容類型和用戶代理。 不要忘記設置內容長度值,因為它是必需的。
  5. 將整個SOAP請求寫入輸出流。
  6. 調用方法建立連接並接收響應(在我的情況下,我使用getResonseCode )。
  7. 如果您收到的回复代碼為
    1. 這意味著您已成功調用Web服務。
  8. 現在在同一個HTTP連接上獲取輸入流並接收字符串對象。 這個字符串對像是一個SOAP響應。
  9. 如果響應代碼不是200,則在相同的HTTP對像上採用ErrorInput流,並接收錯誤(如果有)。
  10. 使用SAXParser(在我的情況下)或DOMParaser或任何其他解析機制解析收到的響應。

我已經為Android手機實施了此過程,並且它已成功運行。 即使超過700 KB,我也能夠解析響應。


請下載並添加您的項目的SOAP庫文件文件名: ksoap2-android-assembly-3.4.0-jar-with-dependencies

清理應用程序,然後啟動程序

這是SOAP服務調用的代碼

    String SOAP_ACTION = "YOUR_ACTION_NAME";
    String METHOD_NAME = "YOUR_METHOD_NAME";
    String NAMESPACE = "YOUR_NAME_SPACE";
    String URL = "YOUR_URL";
    SoapPrimitive resultString = null;

    try {
        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        addPropertyForSOAP(Request);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(Request);

        HttpTransportSE transport = new HttpTransportSE(URL);

        transport.call(SOAP_ACTION, soapEnvelope);
        resultString = (SoapPrimitive) soapEnvelope.getResponse();

        Log.i("SOAP Result", "Result Celsius: " + resultString);
    } catch (Exception ex) {
        Log.e("SOAP Result", "Error: " + ex.getMessage());
    }
    if(resultString != null) {
        return resultString.toString();
    }
    else{
        return "error";
    }

結果可能是JSONObject或JSONArray或String

為了您更好的參考, https://trinitytuts.com/load-data-from-soap-web-service-in-android-application/

謝謝。


這是一個在android中使用SOAP Web服務的工作示例。

**注意:***請勿忘記在您的項目中添加ksoap2.jar,並在AndroidManifest文件中添加INTERNET權限*

public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";


private class TestAsynk extends AsyncTask<String, Void, String> {

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        Toast.makeText(getApplicationContext(),
                String.format("%.2f", Float.parseFloat(result)),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                METHOD_NAME);
        request.addProperty(PROPERTY_NAME, params[0]);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(
                SOAP_ADDRESS);
        Object response = null;
        try {

            androidHttpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();
            Log.e("Object response", response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
}




wsdl