android用okhttp发送带header的post请求(参数为键值对格式)

    public static Map sendPost_body(String url, Map map_header, Map map_body) throws 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();
        //添加参数
        FormBody.Builder builder_body = new FormBody.Builder();
        for (String key : map_body.keySet()) {
            builder_body.add(key, Objects.requireNonNull(map_body.get(key)));
        }
        FormBody formBody = builder_body.build();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).headers(headers).post(formBody).build();
        LocalTime startTime = LocalTime.now();//响应开始时间
        Response response = client.newCall(request).execute();
        LocalTime endTime = LocalTime.now();//响应结束时间
        int code = response.code();
        if (code != 200) {
            Log.e(cn.uiautomator.Constants.TAG, url + "\n" + response);
        }
        Map map = new HashMap<>();
        map.put("code", code);
        map.put("entity", Objects.requireNonNull(response.body()).string());
        map.put("responseTime", Duration.between(startTime, endTime).toMillis());
        response.close();
        return map;
    }

 

你可能感兴趣的:(安卓开发)