запуск версии 1.5 клиента ax2 - PullRequest
6 голосов
/ 02 июня 2010

Так что у меня заканчиваются идеи попытаться заставить клиента подключиться к SOAP-сервису, который я запускаю через axis2.

Я попробовал два метода, один из которых заключался в использовании wsdl2java для создания заглушки и связанных клиентских классов, а затем в написании класса Client, который создает сообщения запросов и отправляет их через заглушку. Другой способ - использовать ServiceClient для подключения ..

Оба по-своему терпят неудачу ..

Вариант # 1, каждый раз, когда сообщение отправляется через заглушку, я получаю это обратно:

org.apache.axis2.AxisFault: The input stream for an incoming message is null.
at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:87)
at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:67)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:354)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)

Вариант № 2, каждый раз, когда я запускаю его, я получаю это исключение:

org.apache.axis2.deployment.DeploymentException: org.apache.axis2.transport.local.LocalTransportSender

Вариант № 2 источника:

import javax.xml.stream.XMLStreamException;
import org.apache.axiom.om.OMAbstractFactory; 
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.Constants;
import org.apache.axis2.client.ServiceClient;

public class loyaltyClient {

    private static EndpointReference targetEPR = 
         new EndpointReference(
           "http://localhost:8080/axis2/services/service");

    public static OMElement verifyCustomer(String customer_id) {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace(
                "http://localhost/", "service");
        OMElement method = fac.createOMElement("VerifyCustomer", omNs);
        OMElement value1 = fac.createOMElement("customer_id",omNs);
        OMElement value2 = fac.createOMElement("source_id",omNs);
        OMElement value3 = fac.createOMElement("source_password",omNs);
        OMElement value4 = fac.createOMElement("source_txnid",omNs);
        OMElement value5 = fac.createOMElement("timestamp",omNs);

value1.addChild(fac.createOMText(value1, customer_id));
value2.addChild(fac.createOMText(value2, "source"));
value3.addChild(fac.createOMText(value3, "1234"));
value4.addChild(fac.createOMText(value4, "123"));
value5.addChild(fac.createOMText(value5, "06-01-2010 12:01:01"));
        method.addChild(value1);
        method.addChild(value2);
        method.addChild(value3);
        method.addChild(value4);
        method.addChild(value5);
        return method;
    }

    public static void main(String[] args) {
        try {
            OMElement vctest = loyaltyClient.verifyCustomer("6177740603");
            Options options = new Options();
            options.setTo(targetEPR);

options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

            ServiceClient sender = new ServiceClient();
            sender.setOptions(options);
            OMElement result = sender.sendReceive(vctest);

            String response = result.getFirstElement().getText();
            System.out.println(response);

        } catch (Exception e) { //(XMLStreamException e) {
            System.out.println(e.toString());
        }
    }

}

Ответы [ 2 ]

5 голосов
/ 16 января 2012

Я также столкнулся с ошибкой «Поток ввода для входящего сообщения нулевой» при использовании Axis для подключения к поставщику услуг .Net.

Проблема в том, что .Net не поддерживает функцию, называемую «чанкованное кодирование», по умолчанию Axis разбивает свой заголовок запроса на куски, которые, как предполагается, соответствуют HTTP 1.1.

В любом случае, вы можете отключить эту функцию в Axis, выполнив следующие действия:

// Turn off the Axsis Chunked feature, some service providers (like .Net) don't support chunked headers.
Options options = serviceClient.getOptions();
options.setProperty(HTTPConstants.CHUNKED, Constants.VALUE_FALSE);
serviceClient.setOptions(options);            

Это сработало для меня. При работе со службами .Net необходимо убедиться еще и в возможности указать имя порта и убедиться, что в полезной нагрузке вашего сообщения есть префикс пространства имен для каждого элемента.

Надеюсь, эта информация кому-нибудь поможет.

Cheers, DC

3 голосов
/ 08 июня 2010

С предупреждением, что Axis2 - это глючная куча дерьма , мне недавно пришлось написать клиент Axis2, и я обнаружил, что с использованием по умолчанию ServiceClient () конструктор не работал должным образом - мне пришлось вручную создавать ConfigurationContext и т. д. Я обнаружил, что использование ServiceClient.getOptions() вместо создания new Options() позволило сохранить некоторые данные по умолчанию. Я бы также порекомендовал сбросить options.setTransportInProtocol(...), если он вам действительно не нужен - все должно нормально работать через HTTP без этого. Также вам может потребоваться установить options.setAction(...) в соответствии с «операцией» в вашем WSDL.

Я включил основную часть моего клиента (с удалением конфиденциальной информации) в надежде, что это поможет. Вы, вероятно, можете спокойно игнорировать части, касающиеся адресации, если только вы не планируете использовать WS-Addressing.

ConfigurationContext cfgCtx = null;

try {
    /* Passing null to both params causes an AxisConfiguration to be created that uses
     * the default axis2.xml file, which is included in the axis2 distribution jar.
     * This is ideal for our case, since we cannot pass a full file path (relative
     * paths are not allowed) because we do not know where the customer will deploy
     * the application. This also allows engaging modules from the classpath. */
    cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null , null);
} catch (AxisFault e) {
    // Bubble up the error
}

ServiceClient svcClient = null;
try {
    svcClient = new ServiceClient(cfgCtx, null);
} catch (AxisFault e) {
    // Bubble up the error
}

try {
    /* This will work with the above ConfigurationContext as long as the module
     * (addressing-1.5.1.mar) is on the classpath, e.g. in shared/lib. */
    svcClient.engageModule("addressing");
} catch (AxisFault e) {
    // Bubble up the error
}

Options opts = svcClient.getOptions();
opts.setTo(new EndpointReference("http://myservername:8080/axis2/services/MyService"));
opts.setAction("urn:doSomething"); // Corresponds to the "operation" in MyService's WSDL
opts.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI); // Set output to SOAP 1.2

SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
svcClient.addHeader(createSOAPSecurityHeader(factory, response)); // CreateSOAPHeader just creates an OMElement

try {
    svcClient.sendReceive(createSOAPBody(factory, response)); // CreateSOAPBody just creates an OMElement
} catch (AxisFault e) {
    throw new ResponseDeliveryException(1, "Error sending SOAP payload.", e);
}
...