如何减少odata4j发送的HTTP请求的超时

时间:2012-06-15 12:56:05

标签: android odata4j

我正在尝试在移动Android应用中使用odata4j库。有时,HTTP请求不会得到响应,因为设备在发送请求后丢失了它的移动连接。在尝试重现它并计时之后,我注意到库大约需要27分钟才能抛出“java.net.SocketException:Connection timed out”。有没有办法减少这个超时,所以我可以更快地处理故障?感谢。

2 个答案:

答案 0 :(得分:3)

使用泽西消费者实现(这是默认设置)。在构建消费者时添加JerseyClientBehavior [1]。这允许您修改ClientConfig [2] - 您可以修改连接+读取超时。

[1] http://code.google.com/p/odata4j/source/browse/odata4j-jersey/src/main/java/org/odata4j/jersey/consumer/behaviors/JerseyClientBehavior.java

[2] http://jersey.java.net/nonav/apidocs/1.1.5.1/jersey/com/sun/jersey/api/client/config/ClientConfig.html

答案 1 :(得分:3)

我想为@John Spurlock answer提供代码段。通过类比代码http://code.google.com/p/odata4j/source/browse/odata4j-jersey/src/main/java/org/odata4j/jersey/consumer/behaviors/AllowSelfSignedCertsBehavior.java

private static ODataJerseyConsumer createOdataConsumer(final String odataServerUrl) {

    Builder builder = ODataJerseyConsumer.newBuilder(odataServerUrl);
    builder.setClientBehaviors(TimeoutBehavior.reduceTimeout());
    return builder.build();
}

private enum TimeoutBehavior implements JerseyClientBehavior {
    INSTANCE;

    @Override
    public ODataClientRequest transform(final ODataClientRequest request) {

        return request;
    }

    @Override
    public void modify(final ClientConfig clientConfig) {

        Map<String, Object> properties = clientConfig.getProperties();
        properties.put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10 * 1000);
        properties.put(ClientConfig.PROPERTY_READ_TIMEOUT, 10 * 1000);
    }

    @Override
    public void modifyClientFilters(final Filterable filterable) {}

    @Override
    public void modifyWebResourceFilters(final Filterable filterable) {}

    public static OClientBehavior reduceTimeout() {

        return TimeoutBehavior.INSTANCE;
    }
}