Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this simple SOAP client not working (org.apache.http)?

I want to send an XML file as a request to a SOAP server. Here is the code I have: (modified from Sending HTTP Post request with SOAP action using org.apache.http )

import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.HttpResponse;
import java.net.URI;

public static void req()   {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String body="xml here";
            String bodyLength=new Integer(body.length()).toString();

            URI uri=new URI("http://1.1.1.1:100/Service");
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader( "SOAPAction", "MonitoringService" );
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");


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

            RequestWrapper requestWrapper=new RequestWrapper(httpPost);
            requestWrapper.setMethod("POST");


            requestWrapper.setHeader("Content-Length",bodyLength);
            HttpResponse response = httpclient.execute(requestWrapper);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Before this I was getting error 'http 500' (internal server error) from the server , but now Im not getting any reply at all. I know that the server works right because with other clients there is no problem.

Thanks.

like image 305
user1523763 Avatar asked Oct 10 '12 20:10

user1523763


2 Answers

org.apache.http API is not SOAP/web service aware and so you're doing the tricky work in a non-standard way. The code is not very java-friendly or flexible, because it can't automatically "bind" (convert) java object data into the SOAP request and out of the SOAP response. It's a little lengthy, tricky to debug and get working, and brittle - are you handling the full SOAP protocol, including fault handling, etc?.

Can I suggest using JAX-WS standard, which is built into the JVM:

1. Save the WSDL file to local disk
E.g. <app path>/META-INF/wsdl/abc.com/calculator/Calculator.wsdl
If you don't have the WSDL, you can type into browser & save result page to disk:
http://abc.com/calculator/Calculator?wsdl

2. Use wsimport command to convert WSDL to java class files
For JDK, tool is in <jdkdir>\bin\wsimport.exe (or .sh).
For an app server, will be something like <app_server_root>\bin\wsimport.exe (or .sh)

<filepath>\wsimport -keep -verbose <wsdlpath>\Calculator.wsdl

OR if your WSDL is available via a pre-existing webservice

<filepath>\wsimport -keep -verbose http://abc.com/calculator/Calculator?wsdl

(you can also include "-p com.abc.calculator" to set the package of generated classes)

Files like the following are generated - include these source files in your java project:

com\abc\calculator\ObjectFactory.java       
com\abc\calculator\package-info.java       
com\abc\calculator\Calculator.java       ............................name = `<wsdl:portType>` name attribute      
com\abc\calculator\CalculatorService.java     ................name = `<wsdl:service>` name attribute    
com\abc\calculator\CalculatorRequestType.java  .......name = schema type used in input message    
com\abc\calculator\CalculatorResultType.java ..........name = schema type used in output message

2. Create a JAX-WS SOAP web service client

package com.abc.calculator.client;

import javax.xml.ws.WebServiceRef;
import com.abc.calculator.CalculatorService;
import com.abc.calculator.Calculator;

public class CalculatorClient {

    @WebServiceRef(wsdlLocation="META-INF/wsdl/abc.com/calculator/Calculator.wsdl")
    // or @WebServiceRef(wsdlLocation="http://abc.com/calculator/Calculator?wsdl")
    public static CalculatorService calculatorService;

    public CalculatorResponseType testCalculation() {
        try {
            CalculatorRequestType request = new CalculatorRequest();
            request.setSomeParameter("abc");
            request.setOtherParameter(3);
            Calculator calculator = calculatorService.getCalculatorPort();
            // automatically generate SOAP XML message, send via HTTP, 
            // receive & marshal response to java object 
            String response = calculator.doCalculation(response);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
like image 153
Glen Best Avatar answered Oct 05 '22 11:10

Glen Best


Try sending the request like this. This is how i did it last time:

try
        {
            StringBuffer strBuffer = new StringBuffer();
            HttpURLConnection connection = connectToEndPoint(endpoint);
            OutputStream outputStream = generateXMLOutput(connection, yourvalue, strDate);

            InputStream inputStream = connection.getInputStream();

            int i;
            while ((i = inputStream.read()) != -1) {
                Writer writer = new StringWriter();
                writer.write(i);
                strBuffer.append(writer.toString());

            String status = xmlOutputParse(strBuffer);

And the functions used:

private static HttpURLConnection connectToEndPoint(String wsEndPoint) throws MalformedURLException, IOException {
    URL urlEndPoint = new URL(wsEndPoint);
    URLConnection urlEndPointConnection = urlEndPoint.openConnection();
    HttpURLConnection httpUrlconnection = (HttpURLConnection) urlEndPointConnection;
    httpUrlconnection.setDoOutput(true);
    httpUrlconnection.setDoInput(true);
    httpUrlconnection.setRequestMethod("POST");
    httpUrlconnection.setRequestProperty("content-type", "application/soap+xml;charset=UTF-8");
    // set connection time out to 2 seconds
    System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(2 * 1000));
    // httpUrlconnection.setConnectTimeout(2*1000);
    // set input stream read timeout to 2 seconds
    System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(2 * 1000));
    // httpUrlconnection.setReadTimeout(2*1000);
    return httpUrlconnection;
}

Where you manually create the xml(modify to your needs):

private static OutputStream generateXMLOutput(HttpURLConnection conn, String msisdn, String strDate) throws IOException {
    OutputStream outputStream = conn.getOutputStream();

    StringBuffer buf = new StringBuffer();

    buf.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ins=\"http://yournamespace">\r\n");
    buf.append("<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">\r\n");

    //..... append all your lines .......       

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");

    outputStreamWriter.write("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ins=\"http://yournamespace\">\r\n");
    outputStreamWriter.write("<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">\r\n");
    //..... write all your lines .......    

    outputStreamWriter.flush();

    outputStream.close();
    return outputStream;
}

And the function which returns your WS answer:

private static String xmlOutputParse(StringBuffer xmlInputParam) throws IOException, ParserConfigurationException, SAXException {
    String status = null;
    DocumentBuilderFactory docBuilderfFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = docBuilderfFactory.newDocumentBuilder();
    InputSource inputSource = new InputSource();
    inputSource.setCharacterStream(new StringReader(xmlInputParam.toString()));
    Document document = documentBuilder.parse(inputSource);
    NodeList nodeList = document.getElementsByTagName("ResponseHeader");
    Element element = (Element) nodeList.item(0);
    if (element == null) {
        return null;
    }
    NodeList name = element.getElementsByTagName("Status");
    Element line = (Element) name.item(0);
    if (line == null) {
        return null;
    }
    if (line.getFirstChild() instanceof CharacterData) {
        CharacterData cd = (CharacterData) line.getFirstChild();
        status = cd.getData().trim();
    }
    return status;
}

I think this solution (even though is long) works on most cases. I hope you can adapt it to your needs.

Best regards !

like image 27
Adrian Zaharia Avatar answered Oct 05 '22 11:10

Adrian Zaharia