Java Timeout调用soap连接的代码行

时间:2015-08-30 16:18:05

标签: java soap timeout

您好我正在执行soap请求。我想运行这行代码。

int flag = 5seconds;

//下面的行不会在5秒内回来)使用soap取消第三方API呼叫并继续

if(时间为5秒) this.soapResponse = soapConnection.call(createSOAPRequest(value),url);

否则 终止并继续使用其余的代码。

我需要存储soapResponse,因此调用其他函数或类可以让我将对象传回来会很糟糕。我想要一种简单的方法来确保该行在标志设置的时间内执行。 我可以创建一个线程并等待5秒钟。如果它没有回来那么只是结束while循环

while(count to 5 seconds){
    this.soapResponse = soapConnection.call(createSOAPRequest(value), url);
}

2 个答案:

答案 0 :(得分:0)

是的,您可以为此创建一个主题。您可以使用this class来实现超时。您需要将SOAP连接调用包装在Runnable中(或者更好,Callable<Response>,因为您想返回一个值):

public class SoapRunnable implements Runnable {
    private String value;
    private String url;
    private Connection soapConnection;
    private Response<?> response;

    public SoapCallable(Connection soapConnection, String value, String url) {
        this.url = url;
        this.value = value;
        this.soapConnection = soapConnection;
    }

    @Override
    public void run() {
        response = soapConnection.call(createSOAPRequest(value), url);
    }

    public Response<?> getResponse() {
        return response;
    }
}

然后,您可以创建SoapRunnable的实例并将其传递给TimeoutController方法:

   try {
      TimeoutController.execute(soapRunnable, 5000);
      // Call succeeded, grab result
      this.soapResponse = soapRunnable.getResponse();
   } catch (TimeoutException e) {
      // call did not return within 5 seconds, proceed with "else" code
   }

答案 1 :(得分:0)

您可以使用以下属性设置超时。

连接超时是连接第三方服务器所花费的时间,读取超时是连接和返回响应后第三方所花费的时间。

    int connectionTimeOutInMs = 5000;
    int readTimeOutInMs = 5000;
    context.put("javax.xml.ws.client.connectionTimeout", connectionTimeOutInMs);    
    context.put("javax.xml.ws.client.receiveTimeout", readTimeOutInMs);
    context.put("com.sun.xml.internal.ws.request.timeout", connectionTimeOutInMs);
    context.put("com.sun.xml.ws.request.timeout", connectionTimeOutInMs);
    context.put("com.sun.xml.ws.connect.timeout", connectionTimeOutInMs);
相关问题