OkHttpClient" open" v2.0中缺少方法

时间:2015-10-23 21:07:38

标签: android okhttp

如果要从Okxttp库从1.x升级到2.x,那么可以看出OkHttpClient方法"打开"不见了。以下代码不会编译。

        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = client.open(url);

2 个答案:

答案 0 :(得分:11)

根据官方change log

URLConnection支持已移至okhttp-urlconnection模块。如果您从1.x升级,此更改将对您产生影响。您需要将okhttp-urlconnection模块添加到项目中,并使用OkUrlFactory创建HttpURLConnection的新实例:

// OkHttp 1.x:
HttpURLConnection connection = client.open(url);

// OkHttp 2.x:
HttpURLConnection connection = new OkUrlFactory(client).open(url);

请记住将以下依赖项添加到Gradle文件中。

compile 'com.squareup.okhttp:okhttp-urlconnection:2.5.0'

答案 1 :(得分:1)

从OkHttp 3.x开始,OkUrlFactory已被标记为已弃用,支持新的Request/Response调用方式,这种方式更灵活。一些信息:https://publicobject.com/2015/12/15/okurlfactory-is-going-away/

所以新风格看起来更像是:

OkHttpClient httpClient = new OkHttpClient()

Request request = Request.Builder()
    .url(url)
    .build()
Response response = httpClient.newCall(request).execute()