如何在android中发送soap请求?

发布于 2024-11-15 15:29:53 字数 1832 浏览 1 评论 0原文

我是 WSDL webservices 的新手,使用 KSoap2 库在 android 中调用 wsdl webservices 。

这是我的肥皂请求转储,

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"; xmlns:loy="http://loyalcard.com/LoyalCardWebService/">;
   <soapenv:Header/>
   <soapenv:Body>
      <loy:GetOffersByLocation>
         <!--Optional:-->
         <loy:Location>
            <!--Optional:-->
            <loy:Latitude>?</loy:Latitude>
            <!--Optional:-->
            <loy:Longitude>?</loy:Longitude>
         </loy:Location>
      </loy:GetOffersByLocation>
   </soapenv:Body>
</soapenv:Envelope>

我传递这个 SopaObject 的方式如下:

 PropertyInfo latitude = new PropertyInfo();
        latitude.name="Latitude";
        latitude.type=Double.class;
        latitude.setValue(32.806673);

   PropertyInfo longitude = new PropertyInfo();
        longitude.name="Longitude";
        longitude.type=Double.class;
        longitude.setValue(-86.791133);

        SoapObject results = null;
        String methodName = "OffersByLocation";
        String actionName = "http://loyalcard.com/LoyalCardWebService/GetOffersByLocation";
        SoapObject request = new SoapObject(NAMESPACE,methodName);

        request.addProperty(latitude);
        request.addProperty(longitude);

这里将纬度和经度值直接传递给 OffersByLocation ,我应该传递元素 Location 。请任何人帮助如何通过 Location 传递参数。

我已经尝试过上述过程,但收到错误消息,

06-17 11:52:55.934: WARN/System.err(350): SoapFault - faultcode: 'soapenv:Server' faultstring: 'org.apache.axis2.databinding.ADBException: Unexpected subelement Latitude' faultactor: 'null' detail: org.kxml2.kdom.Node@44f6ddc0

请任何人告诉我如何在 Soap 对象中传递上述肥皂请求转储?

问候, 斯里尼瓦斯

I am new to WSDL webservices , using KSoap2 library to call wsdl webservices in android .

This is my soap request dump

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"; xmlns:loy="http://loyalcard.com/LoyalCardWebService/">;
   <soapenv:Header/>
   <soapenv:Body>
      <loy:GetOffersByLocation>
         <!--Optional:-->
         <loy:Location>
            <!--Optional:-->
            <loy:Latitude>?</loy:Latitude>
            <!--Optional:-->
            <loy:Longitude>?</loy:Longitude>
         </loy:Location>
      </loy:GetOffersByLocation>
   </soapenv:Body>
</soapenv:Envelope>

I am passing this SopaObject like :

 PropertyInfo latitude = new PropertyInfo();
        latitude.name="Latitude";
        latitude.type=Double.class;
        latitude.setValue(32.806673);

   PropertyInfo longitude = new PropertyInfo();
        longitude.name="Longitude";
        longitude.type=Double.class;
        longitude.setValue(-86.791133);

        SoapObject results = null;
        String methodName = "OffersByLocation";
        String actionName = "http://loyalcard.com/LoyalCardWebService/GetOffersByLocation";
        SoapObject request = new SoapObject(NAMESPACE,methodName);

        request.addProperty(latitude);
        request.addProperty(longitude);

Here am passing latitude and longitude values directly to OffersByLocation , I should pass through element Location . Please can any one help how to pass parameters through Location .

I have tried with above procedure but am getting error saying

06-17 11:52:55.934: WARN/System.err(350): SoapFault - faultcode: 'soapenv:Server' faultstring: 'org.apache.axis2.databinding.ADBException: Unexpected subelement Latitude' faultactor: 'null' detail: org.kxml2.kdom.Node@44f6ddc0

Please can any one tell me how to pass above soap Request dump in Soap Object ?

Regards,
Srinivas

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅笑依然 2024-11-22 15:29:53

您还可以手动构造请求XML,并将其发送到kSOAP进行发送和响应处理。您可以使用soapUI编写请求XML,然后使用诸如{%key%}之类的关键字将它们保存在res/raw中,其中应在运行时放置参数。
以下是替换关键字的代码:

// parse the template and replace all keywords
StringBuffer sb = new StringBuffer();
try {
  // find all keywords
  Pattern patern = Pattern.compile("\\{%(.*?)%\\}");
  Matcher matcher = patern.matcher(templateHtml);

  while (matcher.find()) {
    String keyName = matcher.group(1);
    String keyValue = values.get(keyName);
    if (keyValue == null) {
      keyValue = "";
    }
    // replace the key with value
    matcher.appendReplacement(sb, keyValue);
  }
  matcher.appendTail(sb);

  // return the final string
  return sb.toString();
} catch (Throwable e) {
  Log.e(LOG_TAG, "Error parsing template", e);
  return null;
}

要使用 kSOAP 发送自定义 XML 请求,您需要创建自己的 Transport 类。

或者您可以使用 DefaultHttpClient 手动发送请求(请参阅在 Android 上使用客户端/服务器证书进行双向身份验证 SSL 套接字),并使用 kSOAP只是为了解析响应。

 /**
   * Sends SOAP request to the web service.
   * 
   * @param requestContent the SOAP request XML
   * @return KvmSerializable object generated from the SOAP response XML
   * @throws Exception if the web service can not be
   * reached, or the response data can not be processed.
   */
  public Object sendSoapRequest(String requestContent)
      throws Exception {

    // send SOAP request
    InputStream responseIs = sendRequest(requestContent);

    // create the response SOAP envelope
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

    // process SOAP response
    parseResponse(responseIs, envelope);

    Object bodyIn = envelope.bodyIn;
    if (bodyIn instanceof SoapFault) {
      throw (SoapFault) bodyIn;
    }

    return bodyIn;
  }

  /**
   * Sends SOAP request to the web service.
   * 
   * @param requestContent the content of the request
   * @return {@link InputStream} containing the response content
   * @throws Exception if communication with the web service
   * can not be established, or when the response from the service can not be
   * processed.
   */
  private InputStream sendRequest(String requestContent) throws Exception {

    // initialize HTTP post
    HttpPost httpPost = null;
    try {
      httpPost = new HttpPost(serviceUrl);
      httpPost.addHeader("Accept-Encoding", "gzip,deflate");
      httpPost.addHeader("Content-Type", "text/xml;charset=UTF-8");
      httpPost.addHeader("SOAPAction", "\"\"");
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error initializing HTTP post for SOAP request", e);
      throw e;
    }

    // load content to be sent
    try {
      HttpEntity postEntity = new StringEntity(requestContent);
      httpPost.setEntity(postEntity);
    } catch (UnsupportedEncodingException e) {
      Log.e(LOG_TAG, "Unsupported ensoding of content for SOAP request", e);
      throw e;
    }

    // send request
    HttpResponse httpResponse = null;
    try {
      httpResponse = httpClient.execute(httpPost);
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error sending SOAP request", e);
      throw e;
    }

    // get SOAP response
    try {
      // get response code
      int responseStatusCode = httpResponse.getStatusLine().getStatusCode();

      // if the response code is not 200 - OK, or 500 - Internal error,
      // then communication error occurred
      if (responseStatusCode != 200 && responseStatusCode != 500) {
        String errorMsg = "Got SOAP response code " + responseStatusCode + " "
            + httpResponse.getStatusLine().getReasonPhrase();
        ...
      }

      // get the response content
      HttpEntity httpEntity = httpResponse.getEntity();
      InputStream is = httpEntity.getContent();
      return is;
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error getting SOAP response", e);
      throw e;
    }
  }

  /**
   * Parses the input stream from the response into SoapEnvelope object.
   */
  private void parseResponse(InputStream is, SoapEnvelope envelope)
      throws Exception {
    try {
      XmlPullParser xp = new KXmlParser();
      xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
      xp.setInput(is, "UTF-8");
      envelope.parse(xp);
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error reading/parsing SOAP response", e);
      throw e;
    }
  }

You can also manually construct the request XML, and send it to kSOAP for sending and response processing. You can write your request XML using soapUI, then save them in res/raw with keywords like {%key%} where parameters should be placed at runtime.
Here is the code for replacing the keywords:

// parse the template and replace all keywords
StringBuffer sb = new StringBuffer();
try {
  // find all keywords
  Pattern patern = Pattern.compile("\\{%(.*?)%\\}");
  Matcher matcher = patern.matcher(templateHtml);

  while (matcher.find()) {
    String keyName = matcher.group(1);
    String keyValue = values.get(keyName);
    if (keyValue == null) {
      keyValue = "";
    }
    // replace the key with value
    matcher.appendReplacement(sb, keyValue);
  }
  matcher.appendTail(sb);

  // return the final string
  return sb.toString();
} catch (Throwable e) {
  Log.e(LOG_TAG, "Error parsing template", e);
  return null;
}

To send custom XML request with kSOAP you need to make your own Transport class.

Or you can send the request manually using DefaultHttpClient (see Using client/server certificates for two way authentication SSL socket on Android), and use kSOAP just for parsing the response.

 /**
   * Sends SOAP request to the web service.
   * 
   * @param requestContent the SOAP request XML
   * @return KvmSerializable object generated from the SOAP response XML
   * @throws Exception if the web service can not be
   * reached, or the response data can not be processed.
   */
  public Object sendSoapRequest(String requestContent)
      throws Exception {

    // send SOAP request
    InputStream responseIs = sendRequest(requestContent);

    // create the response SOAP envelope
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

    // process SOAP response
    parseResponse(responseIs, envelope);

    Object bodyIn = envelope.bodyIn;
    if (bodyIn instanceof SoapFault) {
      throw (SoapFault) bodyIn;
    }

    return bodyIn;
  }

  /**
   * Sends SOAP request to the web service.
   * 
   * @param requestContent the content of the request
   * @return {@link InputStream} containing the response content
   * @throws Exception if communication with the web service
   * can not be established, or when the response from the service can not be
   * processed.
   */
  private InputStream sendRequest(String requestContent) throws Exception {

    // initialize HTTP post
    HttpPost httpPost = null;
    try {
      httpPost = new HttpPost(serviceUrl);
      httpPost.addHeader("Accept-Encoding", "gzip,deflate");
      httpPost.addHeader("Content-Type", "text/xml;charset=UTF-8");
      httpPost.addHeader("SOAPAction", "\"\"");
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error initializing HTTP post for SOAP request", e);
      throw e;
    }

    // load content to be sent
    try {
      HttpEntity postEntity = new StringEntity(requestContent);
      httpPost.setEntity(postEntity);
    } catch (UnsupportedEncodingException e) {
      Log.e(LOG_TAG, "Unsupported ensoding of content for SOAP request", e);
      throw e;
    }

    // send request
    HttpResponse httpResponse = null;
    try {
      httpResponse = httpClient.execute(httpPost);
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error sending SOAP request", e);
      throw e;
    }

    // get SOAP response
    try {
      // get response code
      int responseStatusCode = httpResponse.getStatusLine().getStatusCode();

      // if the response code is not 200 - OK, or 500 - Internal error,
      // then communication error occurred
      if (responseStatusCode != 200 && responseStatusCode != 500) {
        String errorMsg = "Got SOAP response code " + responseStatusCode + " "
            + httpResponse.getStatusLine().getReasonPhrase();
        ...
      }

      // get the response content
      HttpEntity httpEntity = httpResponse.getEntity();
      InputStream is = httpEntity.getContent();
      return is;
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error getting SOAP response", e);
      throw e;
    }
  }

  /**
   * Parses the input stream from the response into SoapEnvelope object.
   */
  private void parseResponse(InputStream is, SoapEnvelope envelope)
      throws Exception {
    try {
      XmlPullParser xp = new KXmlParser();
      xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
      xp.setInput(is, "UTF-8");
      envelope.parse(xp);
    } catch (Throwable e) {
      Log.e(LOG_TAG, "Error reading/parsing SOAP response", e);
      throw e;
    }
  }
风渺 2024-11-22 15:29:53

您必须创建自己的 xml 生成器类才能做到这一点。我也在使用相同的程序。反编译 ksoap2 库并研究它们如何生成并根据您的需要更改它。

You have to make your own xml generator class to do that. I am also using the same procedure. decompile the ksoap2 library and study the how they generate and change it as you required..

新一帅帅 2024-11-22 15:29:53

你可以像这样使用。

SoapObject requestObj=new SoapObject(NAMESPACE,"GetOffersByLocation");

SoapObject locationObj=new SoapObject(NAMESPACE,"Location");

 PropertyInfo latitude = new PropertyInfo();
                  latitude.name="Latitude";
                 latitude.type=Double.class;
                 latitude.setValue(32.806673);
                locationObj.addProperty(latitude);

       PropertyInfo longitude = new PropertyInfo();
                longitude.name="Longitude";
                longitude.type=Double.class;
                longitude.setValue(-86.791133);

       locationObj.addProperty(longitude);
       requestObj.addSoapObject(locationObj);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.setOutputSoapObject(requestObj);
        envelope.dotNet = false;
        envelope.bodyOut = request;
        envelope.encodingStyle = SoapSerializationEnvelope.XSD;
         int timeout = 60000;
     String URL="www..........wsdl";
         httpTransportSE = new HttpTransportSE(URL,
         timeout);
         httpTransportSE.debug = true;
         Log.v("request", request.toString());
         httpTransportSE.call(actionName, envelope);

我希望这可以帮助你

谢谢,
柴塔尼亚

You can use like this.

SoapObject requestObj=new SoapObject(NAMESPACE,"GetOffersByLocation");

SoapObject locationObj=new SoapObject(NAMESPACE,"Location");

 PropertyInfo latitude = new PropertyInfo();
                  latitude.name="Latitude";
                 latitude.type=Double.class;
                 latitude.setValue(32.806673);
                locationObj.addProperty(latitude);

       PropertyInfo longitude = new PropertyInfo();
                longitude.name="Longitude";
                longitude.type=Double.class;
                longitude.setValue(-86.791133);

       locationObj.addProperty(longitude);
       requestObj.addSoapObject(locationObj);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.setOutputSoapObject(requestObj);
        envelope.dotNet = false;
        envelope.bodyOut = request;
        envelope.encodingStyle = SoapSerializationEnvelope.XSD;
         int timeout = 60000;
     String URL="www..........wsdl";
         httpTransportSE = new HttpTransportSE(URL,
         timeout);
         httpTransportSE.debug = true;
         Log.v("request", request.toString());
         httpTransportSE.call(actionName, envelope);

I hope this may help u

Thanks,
Chaitanya

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文