安装在使用OkHttp前,我们需要先导入OkHttp的第三方库。 我们可以在Github上找到她的项目地址: https://github.com/square/okhttp 我们可以在Android Studio中使用Gradle, 最后效果如下: 测试使用我们的OKHttp第三方库1.第一步我们需要去创建一个 OKHttpClient 对象OkHttpClient okHttpClient = new OkHttpClient();
2.下一步我们还需要一个 Request 对象,她可以已如下方式被创建Request request = new Request.Builder() .url(requestUrl) .build(); requestUrl是一个字符串变量代表这个URL是为了JSON请求(The requestUrl is a String variable representing the Url for the JSON request.) 在这个测试中,我们将会使用如下的URl:http:///api/v1/random?format=json 3.再下一步我们需要实例化一个 Call 对象Call call = okHttpClient.newCall(request);
Call对象会取走我们的 okHttpClient对象 和 我们的 request对象。
4.在实例化Call对象后,我们现在可以 Execute(执行)她。Executing一个Call后将会返回一个 Response,并且会抛出一个 IOException的异常,这就是为什么们会用一个try,catch块包裹她。
5.执行完我们的Call后,我们需要通过使用 response.isSuccessful()来检查Call对象是否执行成功,通过response.isSuccessful()的返回值为true或者是false来判断。这我们仅仅是一个测试,如果Call成功的话,我们将会通过Log来打印我们的response。try{ Response response = call.execute(); if(response.isSuccessful()){ //The call was successful.print it to the log Log.v("OKHttp",response.body().string()); } }catch(IOException e){ e.printStackTrace(); }
6.测试Code!这是新手一个常见的错误。在Android中不允许任何网络的交互在主线程中进行。It disallows it to force developers to use asynchronous callbacks.(能力有限这句话不敢强译)。但是现在,我们的代码看起来看起来十分的号好!下面我们来看看如何修复这个问题。
7.Fix issue为了修补这个问题,我们只需要让我们的Call执行在非主线程内,所以利用一个 asynchronous callback(异步的callBack)。 让我们call异步的方法是通过调用我们Call对象的 enqueue()方法。 call.enqueue(new Callback()) { @Override public void onFailure( Request request, IOException e ) { } @Override public void OnResponse( Response response) throws IOException { try { if(response.isSuccessful()){ //The call was successful. print it to the log log.v("OKHttp",response.body.string()); } }catch (IOException e) { e.printStackTrace(); } } });
8.在我们再次执行我们的code之前,我们还需要再改一改。如果我们想要现在执行她,我们可能还会接收到错误的提示,因为我们应用的程序没有得到相应的相应的网络权限。所以我们需要再AndroidManifest.xml中添加应用权限。<uses-permission android:name="android.permission.INTERNET"/>
9.当我们执行完code后,我们将接受到如下的log输出:
10.This means, we are now able to execute asynchronous network calls and use the data inside the callback method, when it is ready!
写完后,瞬间爽朗起来。虽然还有问题。 译文来自:https:///tutorial/android-tutorial-part-5-using-okhttp/
http://www./android-basic
https://github.com/square/okhttp/wiki/Recipes
|
|
来自: 昵称10504424 > 《工作》