Как использовать KSoap 2 в Android - PullRequest
10 голосов
/ 01 марта 2011

Я только что натолкнулся на ksoap2 для использования моих собственных asp .net веб-сервисов в приложениях для Android.Я нашел несколько отличных ресурсов через Интернет, и я реализовал свой веб-сервис в приложении для Android.

Ниже приведен ответ веб-сервиса, который я потреблял:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?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>
    <CheckAuthenticationResponse xmlns="http://tempuri.org/">
      <CheckAuthenticationResult>boolean</CheckAuthenticationResult>
    </CheckAuthenticationResponse>
  </soap:Body>
</soap:Envelope>

За использование вышеуказанного сервиса, который я реализовалследующий код:

public static Boolean isAuthenticated(String UserName, String Password)
{
    String NAMESPACE = "http://tempuri.org/";
    String METHOD_NAME = "CheckAuthentication";
    String SOAP_ACTION = "http://tempuri.org/CheckAuthentication";
    String URL = "http://primehangout.com/primehangoutweb.asmx";

    SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
    PropertyInfo pi = new PropertyInfo();
    pi.setName("UserId");
    pi.setValue(UserName);
    pi.setType(String.class);
    Request.addProperty(pi);

    PropertyInfo pi2 = new PropertyInfo();
    pi2.setName("Password");
    pi2.setValue(Password);
    pi2.setType(String.class);
    Request.addProperty(pi2);


    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(Request);
    try
    {
    AndroidHttpTransport transp = new AndroidHttpTransport(URL);
    transp.call(SOAP_ACTION, envelope);
    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

    return Boolean.parseBoolean(result.toString());
    }
    catch(Exception e)
    {

    }


    return false;
}

Работает нормально .. Но теперь я собираюсь использовать сервис.Формат запроса требуемой службы следующий:

POST /primehangoutweb.asmx HTTP/1.1
Host: primehangout.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/GetComment"

<?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:Header>
    <AuthSoapHd xmlns="http://tempuri.org/">
      <strUserName>string</strUserName>
      <strPassword>string</strPassword>
    </AuthSoapHd>
  </soap:Header>
  <soap:Body>
    <GetComment xmlns="http://tempuri.org/">
      <UId>string</UId>
      <refID>int</refID>
    </GetComment>
  </soap:Body>
</soap:Envelope>

А ответ требуемой службы следующий:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

    <?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>
        <GetCommentResponse xmlns="http://tempuri.org/">
          <GetCommentResult>
            <xsd:schema>schema</xsd:schema>xml</GetCommentResult>
        </GetCommentResponse>
      </soap:Body>
    </soap:Envelope>

Я пользовался теми же службами в моем предыдущем приложении для iPhone с использованием классов XMLReaderно, поскольку я новичок в Android, мне нужна ваша помощь, ребята.

:)

Спасибо всем за чтение моего поста!

1 Ответ

1 голос
/ 16 июля 2018

Для интеграции KSoap 2 Вы должны добавить зависимость к вашему файлу build.gradle.

repositories {
    maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}

dependencies {
    compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.2'
 }

Изменить AndroidManifest.xml Для того, чтобы мыльные вызовы веб-службы были доступны в Интернете, необходимо добавить дополнительные разрешения.

<uses-permission android:name="android.permission.INTERNET" />

Затем погрузиться в код

Thread thread = new Thread() {
            @Override
            public void run() {
                String SOAP_ACTION = "https://www.w3schools.com/xml/FahrenheitToCelsius";
                String METHOD_NAME = "FahrenheitToCelsius";
                String NAMESPACE = "https://www.w3schools.com/xml/";
                String URL = "https://www.w3schools.com/xml/tempconvert.asmx";

                //Initialize soap request
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                //Use this to add parameters
                request.addProperty("Fahrenheit", "10");

                //Declare the version of the SOAP request
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                try {
                    //Needed to make the internet call
                    HttpTransportSE transport = new HttpTransportSE(URL);
                    List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
                    headerList.add(new HeaderProperty("Authorization", "Basic " + Base64.encode((username + ":" + password).getBytes())));

                    transport.call(SOAP_ACTION, envelope, headerList);
                    //Get the Response from the envelope body.
                    SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
                } catch (Exception e) {
                    Log.e("TESTS", "KSOAP2", e);
                }
            }
        };

        thread.start();
...