2012-05-20 22 views
12

Estoy tratando de escribir una solicitud de publicación de HTTP codificada con acción SOAP, usando la API org.apache.http. Mi problema es que no encontré la forma de agregar un cuerpo de solicitud (en mi caso, acción SOAP). Estaré encantado de recibir alguna orientación.Enviando solicitud de HTTP Post con acción SOAP usando org.apache.http

import java.net.URI; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.impl.client.RequestWrapper; 
import org.apache.http.protocol.HTTP; 

public class HTTPRequest 
{ 
    @SuppressWarnings("unused") 
    public HTTPRequest() 
    { 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      String body="DataDataData"; 
      String bodyLength=new Integer(body.length()).toString(); 
      System.out.println(bodyLength); 
//   StringEntity stringEntity=new StringEntity(body); 

      URI uri=new URI("SOMEURL?Param1=1234&Param2=abcd"); 
      HttpPost httpPost = new HttpPost(uri); 
      httpPost.addHeader("Test", "Test_Value"); 

//   httpPost.setEntity(stringEntity); 

      StringEntity entity = new StringEntity(body, "text/xml",HTTP.DEFAULT_CONTENT_CHARSET); 
      httpPost.setEntity(entity); 

      RequestWrapper requestWrapper=new RequestWrapper(httpPost); 
      requestWrapper.setMethod("POST"); 
      requestWrapper.setHeader("LuckyNumber", "77"); 
      requestWrapper.removeHeaders("Host"); 
      requestWrapper.setHeader("Host", "GOD_IS_A_DJ"); 
//   requestWrapper.setHeader("Content-Length",bodyLength);   
      HttpResponse response = httpclient.execute(requestWrapper); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

dónde está el código que usted tiene escrito – Satya

+0

añadido dentro ... 10x! – SharonBL

Respuesta

4

... using org.apache.http api. ...

necesita incluir SOAPAction como una cabecera en la petición. Como tiene los identificadores httpPost y requestWrapper, hay tres maneras de agregar el encabezado.

1. httpPost.addHeader("SOAPAction", strReferenceToSoapActionValue); 
2. httpPost.setHeader("SOAPAction", strReferenceToSoapActionValue); 
3. requestWrapper.setHeader("SOAPAction", strReferenceToSoapActionValue); 

La única diferencia es que addHeader permite múltiples valores con el mismo nombre de encabezado y setHeader sólo permite nombres de encabezado único. setHeader(... sobre escribe el primer encabezado con el mismo nombre.

Puede ir con cualquiera de estos en su requisito.

+0

10x! Funciona muy bien :-) – SharonBL

+0

@Ravinder ¿Puedes mirar la pregunta de mis amigos aquí: http://stackoverflow.com/questions/12827900/why-is-this-simple-soap-client-not-working-org-appache- http – quilby

6

Este es un ejemplo de trabajo completo:

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

public void callWebService(String soapAction, String soapEnvBody) { 
    // Create a StringEntity for the SOAP XML. 
    String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>"; 
    StringEntity stringEntity = new StringEntity(body, "UTF-8"); 
    stringEntity.setChunked(true); 

    // Request parameters and other properties. 
    HttpPost httpPost = new HttpPost("http://example.com?soapservice"); 
    httpPost.setEntity(stringEntity); 
    httpPost.addHeader("Accept", "text/xml"); 
    httpPost.addHeader("SOAPAction", soapAction); 

    // Execute and get the response. 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpResponse response = httpClient.execute(httpPost); 
    HttpEntity entity = response.getEntity(); 

    String strResponse = null; 
    if (entity != null) { 
     strResponse = EntityUtils.toString(entity); 
    } 
} 
+0

Estoy intentando su código y obtengo esta excepción: 'java.net.SocketException: El software provocó que la conexión abortara: recv failed'. Tengo httpclient-4.5.2.jar y httpcore-4.4.4.jar en mis classpaths. ¿Alguna idea? –

0

La forma más sencilla de identificar lo que hay que establecer en la acción de jabón cuando se invoca el servicio WCF a través de un cliente en java que cargar el WSDL, vaya a la operación nombre que coincide con el servicio. A partir de ahí, seleccione el URI de acción y configúrelo en el encabezado de acción de soap. Estás listo.

por ejemplo: a partir de WSDL

<wsdl:operation name="MyOperation"> 
    <wsdl:input wsaw:Action="http://tempuri.org/IMyService/MyOperation" message="tns:IMyService_MyOperation_InputMessage" /> 
    <wsdl:output wsaw:Action="http://tempuri.org/IMyService/MyServiceResponse" message="tns:IMyService_MyOperation_OutputMessage" /> 

Ahora en el código java debemos establecer la acción de jabón como el URI de acción.

//The rest of the httpPost object properties have not been shown for brevity 
string actionURI='http://tempuri.org/IMyService/MyOperation'; 
httpPost.setHeader("SOAPAction", actionURI); 
0

Se estaba dando código de respuesta HTTP como un error,

por lo que añade

httppost.addHeader("Content-Type", "text/xml; charset=utf-8"); 

Todo bien ahora, Http: 200

+0

¿Podría explicar por qué agregar esto ayudó con el error? – SuperBiasedMan