package cgg.com.scg.Utils; import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * author: shichenguang * date: 2018/1/3 11:54 * email: none */ public class NetUtls { private MyCallBack myCallBack; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int tab = msg.what; String json = (String) msg.obj; switch (tab) { case 0: myCallBack.mError("请求失败!"); break; case 1: myCallBack.mSucceed(json); break; } } }; public NetUtls(String url) { // 创建okHttpClient OkHttpClient okHttpClient = new OkHttpClient(); // 获取请求对象 final Request request = new Request.Builder().url(url).build(); // 获取Call Call call = okHttpClient.newCall(request); // 执行请求 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) {// 失败回调 Log.e("TAG", e.getMessage().toString()); Message msg = new Message(); msg.what = 0 ; msg.obj = "请求失败"; handler.sendMessage(msg); } @Override public void onResponse(Call call, Response response) throws IOException { // Log.e("TAG", response.body().string()); Message msg = new Message(); msg.what = 1 ; msg.obj = response.body().string(); //msg.obj = "How are you"; handler.sendMessage(msg); } }); } // 创建内部接口 public interface MyCallBack { void mError(String err); void mSucceed(String succeed); } public void setMyCallBack(MyCallBack myCallBack){ this.myCallBack = myCallBack; } }
package cgg.com.scg; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import cgg.com.scg.Utils.NetUtls; public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.tv); NetUtls netUtls = new NetUtls("http://blog.csdn.net/u011692041/article/details/51371367"); netUtls.setMyCallBack(new NetUtls.MyCallBack() { @Override public void mError(String err) { textView.setText(err); } @Override public void mSucceed(String succeed) { textView.setText(succeed); } }); } }