使用android调用Web服务

时间:2014-02-04 06:45:36

标签: android web-services

我有一个返回ArrayOfString的Web服务方法。我必须从Android应用程序调用该Web服务方法。但到目前为止我写的代码不起作用。它给出了ClassCastException。

    SoapObject request = null;
    Object response = null;
    String[] responseStr;

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

    int Timeout = 15 * 1000;
    HttpTransportSE httpTransport = new HttpTransportSE(
            Common.SOAP_ADDRESS, Timeout);

    httpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

    try {

        request = new SoapObject(Common.WSDL_TARGET_NAMESPACE,
                Common.OPERATION_NAME_GET_RESPONDENT_TYPE);

        envelope.setOutputSoapObject(request);
        httpTransport.call(Common.SOAP_ACTION_GET_RESPONDENT_TYPE,envelope);

        response = envelope.getResponse();

        responseStr = (String[]) response;          

        return responseStr;

    } catch (Exception e) {
        e.printStackTrace();
        return null;    
    }

我的代码有什么问题?怎么做? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此功能:

public class CallSoap 
{
    public String SOAP_ACTION = "http://tempuri.org/CreateEvent";

    public String OPERATION_NAME = "CreateEvent"; 

    public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

    public String erorr="";

    public  final String SOAP_ADDRESS = "http://xxxxx/Service1.asmx";

    SoapObject request;
    SoapSerializationEnvelope envelope;

    //AndroidHttpTransport androidHttpTransport;
    HttpTransportSE androidHttp;
public CallSoap() 
{ 
}


protected void SetEnvelope() {

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        // Creating SOAP envelope           
        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        //You can comment that line if your web service is not .NET one.
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);
        androidHttp = new HttpTransportSE("http://10.0.2.2:54869/Service1.asmx");
       // androidHttpTransport = new AndroidHttpTransport("http://10.0.2.2:54869/Service1.asmx");
        androidHttp.debug = true;

    } catch (Exception e) {
        System.out.println("Soap Exception---->>>" + e.toString());    
    }
}

public String[] Save()
{
    try
        {
            androidHttp.call(SOAP_ACTION, envelope);
            //Vector<String> result = null;
            //result = (Vector<String>) envelope.getResponse();
            String result = envelope.getResponse().toString();
            return result;
        }
    catch (Exception exception)
        {
            return exception.toString();
        }

    }