如果要从Okxttp库从1.x升级到2.x,那么可以看出OkHttpClient方法"打开"不见了。以下代码不会编译。
OkHttpClient client = new OkHttpClient();
HttpURLConnection conn = client.open(url);
答案 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()