android Okhttp 的使用教程

本文详细介绍了使用OkHttp进行网络请求的方法,包括GET和POST请求的实现方式,以及如何通过表单形式上传数组数据。文章提供了具体的代码示例,帮助读者理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

github:
https://github.com/anymyna/ui

1、get 请求

    final Request request=new Request.Builder()
            .get()
            .tag(this)
            .url("https://api.github.com/events")
            .build();


    new Thread(new Runnable() {
        @Override
        public void run() {
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    Log.i(Tag,"response:" + response.body().string());
                } else {
                    throw new IOException("Unexpected code " + response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

2、Post 请求

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();
    FormBody formBody = new FormBody.Builder()
            //.add("name", name).add("pwd", pwd)
            .build();

    Request request = new Request.Builder()
            .post(formBody)
            .url("http://httpbin.org/post")
            .build();
    
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            Log.i(Tag,"response:" + response.body().string());

        }
    });

3、Post 以表单的形式来上传数组

    FormBody.Builder builder = new FormBody.Builder();
    builder.add("cate[]",arrayTest[0]);
    builder.add("cate[]",arrayTest[1]);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值