OkHttpClient

在这里插入代码片
 

public class MainActivity extends AppCompatActivity {
    String url ="http://172.17.8.100/small/commodity/v1/bannerShow";
    String registerUrl="http://172.17.8.100/small/user/v1/register";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过OKHttp获取网络数据
          getData();
    //    postData();


    }

    private void postData() {
        //1创建OkHttp对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2创建RequestBody请求体,封装参数
        FormBody requestBody = new FormBody.Builder()
                .add("phone", "13011067611")
                .add("pwd", "123")
                .build();
        //3创建request请求
        final Request request = new Request.Builder().url(registerUrl).post(requestBody).build();
        //4执行请求
        Call call = okHttpClient.newCall(request);
        //5执行异步
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.d("xxx",json);
            }
        });


    }

    private void getData() {
        //1创建OkHttp对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2创建Request请求方式
        Request request = new Request.Builder().url(url).build();
        //3执行请求
        Call call = okHttpClient.newCall(request);
        //4执行异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.d("xxx",json);
            }
        });


    }
}


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值