Skip to content

Setting socket read timeout with javax.xml.soap.SOAPConnection

I am using the javax.xml.soap API (javax.xml.soap.SOAPConnectionFactory, javax.xml.soap.SOAPConnection, and friends) to make a web service call to a remote server, for the most part with great success.

However, sometimes there is a problem and the program gets stuck reading forever.

To address this, I’d like to add a read timeout.

I found several ways it might be possible to achieve this, but they all seemed pretty bad.

So my question to the community is: What is the best way to implement a read timeout behaviour when using the javax.xml.soap API to make a call?



You have to create your own URLStreamHandler so that you can set URLConnection parameters like connection timeout and read timeout.

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
URL endpoint =
  new URL(new URL(""),
          new URLStreamHandler() {
            protected URLConnection openConnection(URL url) throws IOException {
              URL target = new URL(url.toString());
              URLConnection connection = target.openConnection();
              // Connection settings
              connection.setConnectTimeout(10000); // 10 sec
              connection.setReadTimeout(60000); // 1 min

SOAPMessage result =, endpoint);

I have removed some try/catch for clarity.

9 People found this is helpful