【安卓开发】Android初级开发(okhttp3发送带header与带参数的GET请求)

1.首先需要先加入相应依赖

dependencies{implementation 'com.squareup.okhttp3:okhttp:3.13.1'
implementation 'com.squareup.okio:okio:2.2.2'}

2.加入互联网权限

    <!-- 互联网 -->
    <uses-permission android:name="android.permission.INTERNET" /> <!-- 查看网络状态 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 开关网络状态 -->
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

3.加入网络白名单 

相关链接

package xxxxxxxxxxxxxxxxxxx;

import android.util.Log;

import java.io.IOException;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtils {
    //发送get请求,带参数
    public static Map<String, Object> sendGet_body(String url, Map<String, String> map_header, Map<String, String> map_body) throws IOException, IOException {
        //添加header
        Headers.Builder builder_header = new Headers.Builder();
        for (String key : map_header.keySet()) {
            builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
        }
        Headers headers = builder_header.build();
        //添加body
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        for (String key : map_body.keySet()) {
            Log.d(key,Objects.requireNonNull(map_body.get(key)));
            urlBuilder.addQueryParameter(key, map_body.get(key));
        }
        //发送请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(urlBuilder.build()).headers(headers).build();
        LocalTime startTime = LocalTime.now();//响应开始时间
        Response response = client.newCall(request).execute();
        LocalTime endTime = LocalTime.now();//响应结束时间
        int code = response.code();
        Log.d("HTTP返回代码",String.valueOf(code));
        if (code != 200) {
            Log.e("HTTP连接提示", "http连接失败");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        Log.d("获取body内容",Objects.requireNonNull(response.body()).string());
        response.close();
        return map;
    }

}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页
实付 99.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值