Android:okhttp发送请求并且添加token至header头(post+get)

本文介绍了使用OkHttp进行POST和GET请求的具体实现方式,并展示了如何处理响应结果。包括设置请求头、构建请求体及使用回调处理成功或失败的情况。

拦截器没搞懂就先搞这个法子暂时先写到请求里面,不然api接口啥都用不了,其实也并不是特别麻烦,后续要改,不考虑使用拦截器的话,可能要使用到sqlite数据库,emmmm,想想还是别这么干

 public void postTest(){
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
                .add("event_id","33")
                .build();

        Request request = new Request.Builder().url(DecryptionAddress+"app/event/accept").
                addHeader("Token","服务器获取的token").post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                   String result = response.body().string();
                    System.out.println(result);
                }
            }
        });
    }
    public void getTest(){
        //get请求
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(DecryptionAddress+"/app/event/detail?event_id=89")
                .addHeader("Token","服务器获取的token")
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                    System.out.println(result);
                }
            }
        });
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wenlong Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值