OkHttp是一个高效的HTTP客户端,
- 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
- 连接池减少请求延时
- 缓存响应内容,避免一些完全重复的请求
- 透明的GZIP压缩减少响应数据的大小
需要添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.0.0-RC1'
implementation 'com.squareup.okio:okio:2.2.2'
可以右键module打开module设置搜索okhttp依赖添加
public class MainActivity extends AppCompatActivity { String url = "http://wwww.baidu.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new Thread(runnable).start(); } Runnable runnable=new Runnable() { @Override public void run() { OkHttpClient okHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .url(url) .get()//默认就是GET请求,可以不写 .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("输出:", "onFailure: "); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d("输出:", "onResponse: " + response.body().string()); } }); } }; }