OkHttp连接超时

时间:2016-03-15 11:23:07

标签: android okhttp

OkHttp允许您设置连接超时,如

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(connectTimeout, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(readTimeout, TimeUnit.SECONDS);

以下理解是否正确?

连接超时 - 这是使用服务器

创建连接之前的超时

读取超时 - 这是连接在飞行中的时间,无论是否正在读取数据,都会超时。

基于此,读取超时期间打开的连接会发生什么? OkHttp会让服务器知道连接因超时而关闭吗?一旦有读取超时,我想关闭与服务器的连接。我不认为OkHttp(2.2.0)正在发送一个接近服务器的套接字。这可能与SO上的this问题有关。

2 个答案:

答案 0 :(得分:2)

如果OkHttp为您提供回复,您将负责关闭其回复正文。执行此操作的最佳方法是使用try / finally子句。

            if(OS_IOS){
                Ti.API.debug("Media: " + this.get("media").nativePath);
                var infile = Ti.Filesystem.getFile(this.get("media").nativePath); //!
            }else{
                var infile = Ti.Filesystem.getFile(this.get("media"));
            }
            Ti.API.debug('infile: ' + infile.exists());

            var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "videos/");

            if(!tempFile.exists())
                tempFile.createDirectory(); //create videos directory

            var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "videos/" + new Date().getTime() + ".mp4");
            Ti.API.debug('tempFile ' + tempFile.exists()); // tempsFile is always empty

            if(OS_IOS){

                if (infile.exists() && (!tempFile.exists()) ) { //copy infile to videos/
                    tempFile.write(infile.read());
                }

            }else{ //Android

                infile.copy(tempFile.nativePath); //copy infile to videos/
            }   

//Get video, the path saved is correct
    var vid = Ti.Filesystem.getFile(video.get("videoFile"));

答案 1 :(得分:1)

ConnectionTimeOut是TCP握手发生的超时时间。所以它是客户端和服务器之间的连接。

ReadTimeOut是等待读取数据的超时。如果服务器在超时内的最后一个字节之后发送一个字节失败,则会引发读取超时错误。

因此,您将自动关闭连接。所以你必须要执行异常处理。