2012-03-06 3 views
0

У меня есть приложение, которое подключается к нашему веб-сервису .NET, и я нахожу, что мы создаем тот же метод для каждого метода веб-службы, но единственное отличие - это параметры и веб-сервис метод. Я ищу способ, чтобы следующий метод принимал параметры, и тогда было бы более полезно управлять 1 против нескольких.Параметры передачи для метода SOAP

Текущий метод * ИмяСпространение, URL, argName, argValue определены в верхней части класса.

public static Document GetTickets() { 
    try { 
     SoapObject request = new SoapObject(NameSpace, "GetTickets");   
     HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 
     request.addProperty(argName, argValue); 

     request.addProperty("Customer", "ABC"); 
     request.addProperty("Local", "USA"); 

     envelope.setOutputSoapObject(request); 
     androidHttpTransport.call("RemoteWebService/GetTickets", envelope); 

     SoapPrimitive responseData = (SoapPrimitive) envelope.getResponse(); 
     if (responseData != null) 
     { 
      //get the factory 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      //Using factory get an instance of document builder 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      //parse using builder to get DOM representation of the XML file 
      InputSource is = new InputSource(new StringReader(responseData.toString())); 
      return db.parse(is); 
     } 
     else 
      return null; 
    } 
    catch (Exception e) 
    { 
     Errors.LogError(e); 
     return null; 
    } 
} 

Я хотел бы, чтобы это было что-то вдоль этих линий:

public static Document GetTickets(String WebServiceMethod, ArrayList Params) { 
    try { 
     SoapObject request = new SoapObject(NameSpace, WebServiceMethod);   
     HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 

     //Syntax is wrong, I know, but just want to show what I'm looking to do: 
     foreach(Parameter p in Params) 
      request.addProperty(p[0].value, p[1].value); 

     envelope.setOutputSoapObject(request); 
     androidHttpTransport.call("RemoteWebService/" + WebServiceMethod, envelope); 

     SoapPrimitive responseData = (SoapPrimitive) envelope.getResponse(); 
     if (responseData != null) 
     { 
      //get the factory 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      //Using factory get an instance of document builder 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      //parse using builder to get DOM representation of the XML file 
      InputSource is = new InputSource(new StringReader(responseData.toString())); 
      return db.parse(is); 
     } 
     else 
      return null; 
    } 
    catch (Exception e) 
    { 
     Errors.LogError(e); 
     return null; 
    } 
} 

Я попробовал несколько разных попыток это, но получая много ошибок. Я знаю, что это довольно просто, но, похоже, не может понять это.

+0

Вы можете отправить сообщение об ошибке? – rodrigoap

+0

Ну, как я уже сказал, я попробовал это с массивом, многомерным массивом и несколькими другими, но продолжал получать ошибку индекса вне диапазона, что, как я знаю, означает, что индекс элемента, к которому обращаются, находится за пределами границы массива, но я был так расстроен этим, что я удалил все и снова начал с нуля. Извините, у меня нет ошибки. – Robert

ответ

1

Я, кажется, понял, хороший подход, но приветствуем любую обратную связь, чтобы, если это нормально или нет:

создал класс с именем параметра:

public class Parameter { 

    private String mParameterName; 
    private String mParameterValue; 

    // [[ ParameterName 

    public void setParameterName(String ParameterName){ 
     mParameterName = ParameterName; 
    } 

    public String getParameterName(){ 
     return mParameterName; 
    } 

    // ]] 

    // [[ ParameterValue 

    public void setParameterValue(String ParameterValue){ 
     mParameterValue = ParameterValue; 
    } 

    public String getParameterValue(){ 
     return mParameterValue; 
    } 

    // ]] 
} 

А затем изменил мой метод, чтобы принять Список такого типа:

public static Document GetWebServiceData(String WebServiceMethod, List<Parameter> Params) { 
    try { 
     SoapObject request = new SoapObject(NameSpace, WebServiceMethod);   
     HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 

     for(Parameter param : Params) 
      request.addProperty(param.getParameterName(), param.getParameterValue()); 

     envelope.setOutputSoapObject(request); 
     androidHttpTransport.call(NameSpace + "/" + WebServiceMethod, envelope); 

     SoapPrimitive responseData = (SoapPrimitive) envelope.getResponse(); 
     if (responseData != null) 
     { 
      //get the factory 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 

      //Using factory get an instance of document builder 
      DocumentBuilder db = dbf.newDocumentBuilder(); 

      //parse using builder to get DOM representation of the XML file 
      InputSource is = new InputSource(new StringReader(responseData.toString())); 
      return db.parse(is); 
     } 
     else 
      return null; 
    } 
    catch (Exception e) 
    { 
     Errors.LogError(e); 
     return null; 
    } 
} 

А потом он просто получает доступ к следующим образом:

List<Parameter> Params = new ArrayList<Parameter>(); 

    Parameter Param = new Parameter(); 
    Param.setParameterName("Customer"); 
    Param.setParameterValue("ABC"); 
    Params.add(Param); 

    Param = new Parameter(); 
    Param.setParameterName("Local"); 
    Param.setParameterValue("USA"); 
    Params.add(Param); 

    Document doc = GetWebServiceData("GetTickets", Params); 

Работает как очарование! Надеюсь, это поможет кому-то еще ...

Смежные вопросы