如何在调用soap客户端时设置连接超时

时间:2015-05-19 08:31:56

标签: java web-services soap

是webservice的新手。我写了一个肥皂客户端,它工作正常。但是,当托管Web服务的服务器没有响应时,我们在“连接超时”位置访问wsdl失败:25秒后打开流问题时连接。在这25秒内,浏览器挂起。所以我想将连接超时限制为5秒。我该怎么设置为5秒?以下是我的代码

URL url=null;
try {
url = new URL(serviceUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
return "ERROR";
}

Service service = new Service(url);//Exception is thrown here
ServiceSoap soap = service.getServiceSoap();

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用:

    url = new URL(serviceURL); // serviceURL is like "http://.../some.asmx"
    String actionUrl = "http://.../SomeService";
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(5000); //5 sec in milliseconds
    connection.setDoOutput( true );
    connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");
    connection.setRequestProperty("SOAPAction", actionUrl);

    String file = (String)request;

        OutputStream reqStream = null;
        try {
            reqStream = connection.getOutputStream();
        } catch (IOException e) {
            throw e;
        }
        try {
            reqStream.write(file.getBytes());
        } catch (IOException e) {
            throw e;
        }

        InputStream resStream = null;
        try {
            resStream = connection.getInputStream();
        } catch (IOException e) {
            throw e;
        }

对于org.apache.cxf,您可以尝试下面的代码

Service service = new Service(wsdl);
ServiceSoap port = service.getServiceSoap();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(5000);
policy.setReceiveTimeout(5000);