使用okhttp3简单执行网络请求

来源:互联网 发布:两个向量相乘的矩阵 编辑:程序博客网 时间:2024/05/16 19:02

使用okhttp3简单执行网络请求

  • 添加依赖库
compile 'com.squareup.okhttp3:okhttp:3.6.0'
  • 开通网络请求权限
 <uses-permission android:name="android.permission.INTERNET" />
import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;/** * Created by Smile on 2017/5/3. */public class HttpUtilWithOkHttp {    public static void sendHttpRequest(final String address, final Callback callback){        new  Thread(new Runnable() {            @Override            public void run() {                OkHttpClient client=new OkHttpClient();                Request request=new Request.Builder().url(address).build();                client.newCall(request).enqueue(callback);            }        }).start();    }}
/*** 执行网络请求*/    private void requestNetwork(){         String url="http://app.zhuashihui.com/api/qunfa";        HttpUtilWithOkHttp httpUtilWithOkHttp=new HttpUtilWithOkHttp();        httpUtilWithOkHttp.sendHttpRequest(url, new Callback() {            @Override            public void onFailure(Call call, IOException e) {                //请求失败            }            @Override            public void onResponse(Call call, Response response) throws IOException {                //请求成功                String responseStr=response.body().string();                //创建Bundle对象                Bundle bundle=new Bundle();                //请求的结果放进bundle内                bundle.putString("responseStr",responseStr);                //创建一个message对象                Message message=new Message();                //message对象存值                message.setData(bundle);                //发送消息到handle                handler.sendMessage(message);            }        });    }