2012-09-24 31 views
6

Tengo el siguiente código de aplicación de Android a continuación. Estoy intentando conectarme a un servicio web a través de HTTP. El servicio web utiliza el eje apache. Sin embargo, me encuentro con el error "Error al leer XMLStreamReader" en la respuesta. Estoy realmente atascado y no estoy seguro de lo que puedo hacer. ¿Podría ser que hay diferentes versiones de cliente HTTP y SOAP en el servidor y el lado del cliente? Cualquier ayuda sobre esto sería muy apreciada. El servicio web es muy simple: el método sayHello muestra el argumento dado en arg0 = some_stringError de respuesta de envolvente SOAP: Error al leer XMLStreamReader

public class MainActivity extends Activity { 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    BufferedReader in = null; 
    try { 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(
       "http://10.0.0.63:8080/archibus/cxf/HelloWorld/sayHello"); 
     request.addHeader("Content-Type", "text/xml"); 
     List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
     postParameters.add(new BasicNameValuePair("arg0", "testing")); 
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); 
     request.setEntity(formEntity); 

     HttpResponse response = client.execute(request); 

     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
      sb.append(line + NL); 
     } 
     in.close(); 

     String page = sb.toString(); 
     // Log.i(tag, page); 
     System.out.println(page); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (in != null) { 
      try { 
       in.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
} 
+0

http://www.lalit3686.blogspot.in/2012/06/calling-soap-webservice-using- httppost.html –

Respuesta

7

Su petición de servicio Web no está bien construido. En realidad está creando una solicitud de formulario y no una solicitud de SOAP real.

una solicitud SOAP es un documento XML que tiene un sobre y un cuerpo, vea el ejemplo aquí SOAP Message Example on Wikipedia.

Lo que en realidad está haciendo aquí es una llamada HTTP estándar que emula un formulario de envío y no una llamada SOAP.

Tiene dos soluciones aquí:

1- Usted puede emular el comportamiento de un cliente SOAP creando manualmente el documento XML y enviarlo. Además de establecer el documento XML adecuado como petición del cuerpo no se olvide de establecer las cabeceras apropiadas: SOAPAction, Content-Type y Content-Length

 RequestEntity requestEntity = new StringRequestEntity("<?xml version=\"1.0\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"><soap:Header></soap:Header><soap:Body><m:GetStockPrice xmlns:m=\"http://www.example.org/stock\"><m:StockName>IBM</m:StockName></m:GetStockPrice></soap:Body></soap:Envelope>"); 
    post.setRequestEntity(requestEntity); 

Asimismo, no se olvide de cambiar el espacio de nombres (m) por encima con el espacio de nombre apropiado que usa tu servicio web. y el nombre de la operación (GetStockPrice) con la operación que intenta invocar. Además, no olvide los nombres y tipos de parámetros.

2- Usted puede utilizar Apache Axis para generar un cliente y utilizar ese cliente con su solicitud

Ver este tema para obtener más información y un cliente recomendado How to call a SOAP web service on Android

2

Shoukry K es correcto. Has hecho una solicitud HTTP POST. Este no es un servicio web de jabón. Si desea saber cómo llamar a un servicio web, siga el enlace. http://www.youtube.com/watch?v=v9EowBVgwSo. Asegúrese de descargar el último archivo jar de ksoap.

1

Código de ejemplo con K-SOAP para Android.

private void sendSOAPmsg(DamageAssessmentFormPojo pojo) throws IOException, XmlPullParserException, SoapFault { 
     SoapObject request = new SoapObject(WEBSERVICE.NAMESPACE, WEBSERVICE.METHOD_NAME_SUBMIT_REPORT); 
     request.addProperty("xmlBytes", Util.getSoapBase64String(pojo)); 
     request.addProperty("fileName", IO.DefaultReportName); 
     request.addProperty("deviceId", AppConstants.IMEI != null ? AppConstants.IMEI : Util.getIMEI(this)); 

     SoapPrimitive response = sendSOAPEnvelope(request, WEBSERVICE.SOAP_ACTION_SUBMIT_REPORT); 

     if (response.toString().equalsIgnoreCase("true")) { 
      Logger.logInfo("REPORT SENT SUCCESSFULLY", "WEB-SERVICE"); 
      pojo.setReportSent(true); 
      IO.writeObject(pojo.getReportsFolderPath() + IO.DefaultReportName, pojo); 
     } else { 
      Logger.logInfo("REPORT SENT FAILED", "WEB-SERVICE - RESONSE " + response.toString()); 
     } 
    } 

    private SoapPrimitive sendSOAPEnvelope(SoapObject request, String soapAction) throws IOException, XmlPullParserException, SoapFault { 
     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 
     envelope.setOutputSoapObject(request); 
     HttpTransportSE androidHttpTransport = new HttpTransportSE(WEBSERVICE.URL); 

     androidHttpTransport.call(soapAction, envelope); 
     SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 

     return response; 

    } 

    private boolean sendSOAPimage(String strImg, File pFile) throws IOException, XmlPullParserException { 
     boolean result = false; 

     if (strImg != null) { 
      SoapObject request = new SoapObject(WEBSERVICE.NAMESPACE, WEBSERVICE.METHOD_NAME_SUBMIT_IMAGE); 
      request.addProperty("imageBytes", strImg); 
      request.addProperty("fileName", pFile.getName()); 
      request.addProperty("deviceId", AppConstants.IMEI != null ? AppConstants.IMEI : Util.getIMEI(this)); 

      SoapPrimitive response = sendSOAPEnvelope(request, WEBSERVICE.SOAP_ACTION_SUBMIT_MAGE); 

      if (response.toString().equalsIgnoreCase("true")) { 

       result = true; 

       Logger.logInfo("IMAGE SENT SUCCESSFULLY", "WEB-SERVICE"); 

      } else { 
       Logger.logInfo("IMAGE SENT FAILED", "WEB-SERVICE - RESONSE " + response.toString()); 
      } 

     } 

     return result; 
    } 

// -------- Util ayudante Método

public static String getSoapBase64String(DamageAssessmentFormPojo pojo) { 


     XmlSerializer xmlSerializer = Xml.newSerializer(); 
     StringWriter writer = new StringWriter(); 

     try { 
      xmlSerializer.setOutput(writer); 
      xmlSerializer.startDocument("UTF-8", true); 

      xmlSerializer.startTag("", XMLTags.TAG_ROD); 
      xmlSerializer.startTag("", XMLTags.TAG_ORDER); 

      xmlSerializer.startTag("", XMLTags.TAG_SEVERITY); 
      xmlSerializer.text(pojo.getCheckedSeverity_Complexity()); 
      xmlSerializer.endTag("", XMLTags.TAG_SEVERITY); 

      xmlSerializer.startTag("", XMLTags.TAG_DAMAGE_TYPE); 
      StringBuilder builder = new StringBuilder(); 
      for (String str : pojo.getCheckedDamageTypes()) { 

       builder.append(str + " , "); 

      } 
      xmlSerializer.text(builder.toString()); 
      xmlSerializer.endTag("", XMLTags.TAG_DAMAGE_TYPE); 

      xmlSerializer.startTag("", XMLTags.TAG_ENV_IMPACT); 
      xmlSerializer.text(pojo.getCheckedEnvImpact()); 
      xmlSerializer.endTag("", XMLTags.TAG_ENV_IMPACT); 

      xmlSerializer.startTag("", XMLTags.TAG_ENV_COMMENT); 
      xmlSerializer.text(pojo.getEnvImpactComments()); 
      xmlSerializer.endTag("", XMLTags.TAG_ENV_COMMENT); 

      xmlSerializer.startTag("", XMLTags.TAG_TRAVEL_CONDITION); 
      xmlSerializer.text(pojo.getCheckedTravelCond()); 
      xmlSerializer.endTag("", XMLTags.TAG_TRAVEL_CONDITION); 

      xmlSerializer.startTag("", XMLTags.TAG_TRAVEL_COMMENT); 
      xmlSerializer.text(pojo.getTravCondComments()); 
      xmlSerializer.endTag("", XMLTags.TAG_TRAVEL_COMMENT); 

      xmlSerializer.startTag("", XMLTags.TAG_ORDER_DATE); 
      xmlSerializer.text(pojo.getDateTime()); 
      xmlSerializer.endTag("", XMLTags.TAG_ORDER_DATE); 

      xmlSerializer.endTag("", "Order"); 
      xmlSerializer.endTag("", "ROD"); 

      xmlSerializer.endDocument(); 

     } catch (IllegalArgumentException e) { 
      Logger.logException(e); 
     } catch (IllegalStateException e) { 
      Logger.logException(e); 
     } catch (IOException e) { 
      Logger.logException(e); 
     } 

     return Base64.encode(writer.toString().getBytes()); 
    } 
Cuestiones relacionadas