首先打开 Android Studio ,创建名为 OkHttpSample 的 project 。
在使用 OkHttp 之前需要在 build.gradle (Module: app) 文件中的 dependences
闭包下添加 OkHttp 的依赖:
implementation("com.squareup.okhttp3:okhttp:4.5.0")
这只是一个简单的测试,所以只需要在布局文件中添加一个 Button 以及一个 TextView 即可;打开 activity_ok_http_sample.xml 并添加控件:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="GetFunc"
android:text="get"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello OkHttp" />
布局之后回到 OkHttpSample.java 文件,在该类内添加一个对应的 GetFunc
方法,并在该方法内完成调用 OkHttp 的操作:
- 创建
OkHttpClient
的对象okHttpClient
;
OkHttpClient okHttpClient = new OkHttpClient();
- 构造
Request
;
Request.Builder builder = new Request.Builder();
Request request = builder.get().url("https://www.jianshu.com/").build();
- 将
Request
封装为Call
Call call = okHttpClient.newCall(request);
- 执行
call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
为了能够直接看到返回的结果,这里新建一个 MyLog
类用于打印信息:
import android.util.Log;
public class MyLog {
private static final String TAG = "jianshu_okhttp";
private static boolean debug = true;
public static void e(String msg) {
if (debug){
Log.e(TAG, msg);
}
}
}
然后借助刚刚写的 MyLog
类来补充 onFailure
与 onResponse
两个方法:
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
MyLog.e("onFailure" + e.getMessage());
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
MyLog.e("onResponse");
String res = response.body().string();
MyLog.e(res);
}
});
可以在 Logcat 中观察到相应的返回信息
如果要把这些内容在之前添加的 TextView 控件上显示出来,那就需要再多一些工作,首先在 activity_ok_http_sample.xml 中修改:
<TextView
android:id="@+id/mytext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello OkHttp" />
然后在 OkHttpSample
类中声明变量:
private TextView myText;
在 onCreate
方法中添加一行:
myText = (TextView) findViewById(R.id.mytext);
最后就是修改 onResponse
方法,但是由于控件只能在 UI 线程 中被修改,而该方法属于子线程,因此只能够开启 UI 线程后在其中添加显示信息的代码:
runOnUiThread(new Runnable() {
@Override
public void run() {
myText.setText(res);
}
});
Android Studio 升级之后可能会出现 AndroidManifest.xml 里出现大面积 warning 的情况,这是因为 没有为应用程序清单中的相关活动添加过滤器 ,对于这种情况,我们只需要在
intent
中添加一行<action android:name="android.intent.action.VIEW" />
即可