新建类HttpUtil,能够避免在多个界面须要使用网络请求是代码的重复html
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中点击事件代码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); } }); }