OkHttpClient “open” method missing in v2.0

谁说我不能喝 提交于 2019-12-04 03:33:02

问题


If you are upgrading from OkHttp library from 1.x to 2.x, glaringly the OkHttpClient method "open" is missing. The below code will NOT compile.

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

回答1:


As per the official change log:

URLConnection support has moved to the okhttp-urlconnection module. If you're upgrading from 1.x, this change will impact you. You will need to add the okhttp-urlconnection module to your project and use the OkUrlFactory to create new instances of HttpURLConnection:

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

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

Just remember to add the dependency as below to the Gradle file.

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



回答2:


As of OkHttp 3.x, OkUrlFactory had been marked deprecated, in favor of the new Request/Response style of calls, which is more flexible. Some info: https://publicobject.com/2015/12/15/okurlfactory-is-going-away/

So the new style is going to look more like:

OkHttpClient httpClient = new OkHttpClient()

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


来源:https://stackoverflow.com/questions/33311409/okhttpclient-open-method-missing-in-v2-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!