新建类HttpUtil,可以避免在多个界面需要使用网络请求是代码的重复
package com.example.networktest; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by lenovo on 2019/3/19. */ public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback);//内部自动打开了线程 }
Mian.java中点击事件代码
public void onClick(View v){ if (v.getId()==R.id.button1){ // sendRequestWithHttpURLConnection(); // sendRequestWithOkHttp(); HttpUtil.sendOkHttpRequest("https://www.qu.la/book/101104/5290362.html",new okhttp3.Callback(){ @Override public void onResponse(Call call, Response response) throws IOException { String responseData=response.body().string();//获取返回的值 showResponse(responseData);//自己写的方法 } @Override public void onFailure(Call call, IOException e) { } }); } }
private void showResponse(final String response){ runOnUiThread(new Runnable() {//由于子线程不准许操作UI所以使用runOnUiThread方法切换到主线程 @Override public void run() { text.setText(response); } }); }
原文地址:https://www.cnblogs.com/837634902why/p/10557524.html
时间: 2024-10-19 20:54:10