------------恢复内容开始------------
介绍
OkHttp是开源网络请求框架
其中,OkHttpClient,Call ,Request,Response四个主要对象
implementation ‘com.squareup.okhttp3:okhttp:4.4.0‘
方法
( Request )
1. Request Request.Builder.url( String url ).build()
参数:
String url:请求地址
返回值:Request
返回值意义:获取封装的Request对象
作用:封装URL的Request对象
( OkHttpClient )
用来生成请求的调用Call
Call newCall( Request request )
参数:
Request request:请求对象
返回值:Call
返回值意义:生成封装Call的
作用:生成Call对象
( Call )
用来执行请求获取响应
Response execute()
参数:无
返回值:Response
返回值意义:响应对象Response
作用:获取响应对象Response
( Response )
HttpResonse对象,用来获取响应体
String response.body().string()
这个是Kotln代码,不深入。
使用
两Build夹一U ,构造得请求,相似有中介
Thread tht = new Thread(new Runnable() { @Override public void run() { Request request = new Request.Builder().url("http://106.xx.xx.xx:8080/CoolWeather/china").build(); OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request); String string = null; try { Response response = call.execute(); response.b string = response.body().string(); } catch (IOException e) { e.printStackTrace(); } String finalString = string; runOnUiThread(new Runnable() { @Override public void run() { Log.i("MA", "run: "); txt.setText(finalString); } }); } }); tht.start();
原文:https://www.cnblogs.com/remix777/p/15141112.html