Android常用开源库———————————OkHttp的使用方法

大道之行,天下为公。这篇文章主要讲述Android常用开源库———————————OkHttp的使用方法相关的知识,希望能为你提供帮助。
OkHttp是一个优秀的网络通信库,GitHub项目主页地址。
 
基本使用
在项目中中添加OkHttp库的依赖。.

implementation("com.squareup.okhttp3:okhttp:3.12.0")

 
OkHttp进行Get请求
//创建一个OkHttpClient的实例 OkHttpClient client = new OkHttpClient(); //创建一个Request对象 Request request = new Request.Builder().build; //通过url()方法来设置目标的网络地址 Request request = new Request.Builder().url("http://www.baidu.com").build(); //调用newCall()方法来创建一个Call对象 Response response = client.newCall(request).exute(); //Response对象就是服务器返回的数据,通过如下写法得到返回的具体内容 String responseData = https://www.songbingjia.com/android/response.body().string()

 
OkHttp进行Post请求
//构建一个RequestBody对象存放待提交的参数 RequestBody requestBody = new FormBody.Builder().add("username","admin").add("password","12345").build(); //调用post()方法 Request request = new Request.Builder().uirl("http://www.baidu.com").post(requestBody).build();

接下来的操作和Get请求一样
 
同步请求时,需要开启子线程;异步请求时调用enqueue,无需开启子线程。
public class MainActivity extends AppCompatActivityimplements View.OnClickListener{TextView responseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButtonsendRequest = (Button) findViewById(R.id.send_request); Button sendAsyncRequest = (Button) findViewById(R.id.send_asyncRequest); responseText = (TextView) findViewById(R.id.response_text); sendRequest.setOnClickListener(this); sendAsyncRequest.setOnClickListener(this); }@Override public void onClick(View v) { switch (v.getId()) { case R.id.send_request: sendRequestWithOkHttp(); break; case R.id.send_asyncRequest: sendAsyncRequestWithOkHttp(); break; default: break; } }private void sendAsyncRequestWithOkHttp() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com").build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this,"get failed", Toast.LENGTH_SHORT).show(); }@Override public void onResponse(Call call, Response response) throws IOException { final String res = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { responseText.setText(res); } }); } }); }private void sendRequestWithOkHttp() { new Thread(new Runnable() { @Override public void run() { try{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com").build(); Response response = client.newCall(request).execute(); String responseData = https://www.songbingjia.com/android/response.body().string(); showResponse(responseData); } catch (Exception e) { e.printStackTrace(); } } }).start(); }private void showResponse(final String response) { runOnUiThread(new Runnable() { @Override public void run() { responseText.setText(response); } }); } }

【Android常用开源库———————————OkHttp的使用方法】 

    推荐阅读