url参数转json、json转Map<String,String>、Map<String,String>转RequestBody、Okhttp JSON请求、Okhttp GET POST异步请求

该博客详细介绍了如何使用OkHttp进行HTTP请求,包括同步和异步GET、POST操作,以及URL参数转JSON、JSON转Map<String, String>、Map<String, String>转RequestBody的方法。通过这些转换,可以灵活地处理网络请求中的数据格式。

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

url参数转json、json转Map<String,String>、Map<String,String>转RequestBody

    //Map<String,String>转RequestBody
    private RequestBody setRequestBody(Map<String, String> BodyParams){
        RequestBody body=null;
        okhttp3.FormBody.Builder formEncodingBuilder=new okhttp3.FormBody.Builder();
        if(BodyParams != null){
            Iterator<String> iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formEncodingBuilder.add(key, BodyParams.get(key));
            }
        }
        body=formEncodingBuilder.build();
        return body;

    }

//url参数转json
    public static JSONObject getJsonStrByQueryUrl(String paramStr){
        //String paramStr = "a=a1&b=b1&c=c1";
        String[] params = paramStr.split("&");
        JSONObject obj = new JSONObject();
        for (int i = 0; i < params.length; i++) {
            String[] param = params[i].split("=");
            if (param.length >= 2) {
                String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                try {
                    obj.put(key,value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

    //json转Map<String,String>
    public static Map<String,String> JsonToMap(JSONObject j) throws JSONException {

        Map<String,String> map = new HashMap<>();

        Iterator<String> iterator = j.keys();

        while(iterator.hasNext()){

            String key = (String)iterator.next();

            String value = j.getString(key);

            map.put(key, value);

        }

        return map;

    }

ohttp同步请求 json参数

//ohttp同步请求 json参数
    public String  jpost(String url,String json) throws IOException {
        OkHttpClient okHttpClient =new OkHttpClient();
        RequestBody requestBody=RequestBody.create(json, MediaType.parse("application/json"));
        Request request=new Request.Builder().url(url).post(requestBody).build();
        Call call =okHttpClient.newCall(request);
        Response response= call.execute();
        return response.body().string();

    }

Okhttp GET POST异步请求

    public void okget(String url){
        Request.Builder builder=new Request.Builder();
        builder.url(url);
        Request request=builder.build();
        Call call = mOkHttpClient.newCall(request);
        Message message=new Message();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                message.what=0x01;
                message.obj="查询失败,请检查网络";
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                message.what=0x2;
                message.obj=response.body().string();
                mHandler.sendMessage(message);
            }
        });
    }

    public void okpost(String url,RequestBody body,String header){
        Request.Builder builder=new Request.Builder();
        builder.url(url);
        builder.post(body);
        Request request=builder.build();
        Call call = mOkHttpClient.newCall(request);
        Message message=new Message();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                message.what=0x01;
                message.obj="查询失败,请检查网络";
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                message.what=0x3;
                message.obj=response.body().string();
                mHandler.sendMessage(message);
            }
        });
    }


//用handler接收
        mOkHttpClient=new OkHttpClient();
         mHandler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what==0x2){
                //接收get msg.obj
                }else if(msg.what==0x01){
                //失败
                }else if(msg.what==0x03){
                //接收post msg.obj
                }
        };

Handler发送

                     Message message = new Message();
                     message.what = 0x01;
                     message.obj = "666666";
                     mHandler.sendMessage(message);
使用OkHttpClient发送POST请求时,你可以按照以下步骤编写请求方法: 首先,你需要导入必要的库: ```java import okhttp3.*; import java.io.IOException; import java.nio.charset.Charset; import java.util.Map; ``` 然后创建一个发送POST请求的函数,例如: ```java public String sendPostRequest(String apiUrl, Map<String, String> params) throws IOException { OkHttpClient client = new OkHttpClient(); // 创建OkHttpClient实例 // 将参数化为查询字符串或JSON正文,这里假设是一个简单的键值对形式的查询字符串 StringBuilder query = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { if (query.length() > 0) { query.append("&"); // 如果不是第一个参数,添加&字符分隔 } query.append(entry.getKey()).append("=").append(entry.getValue()); } // 构造请求URL请求RequestBody body; if (apiUrl.endsWith("?")) { // 如果URL本身已经包含查询参数,追加新的参数 apiUrl += query.toString(); } else { body = FormBody.Builder() .add("params", query.toString()) .build(); // 如果是POST JSON,可能会使用RequestBody.Builder构建JSON内容 } Request request = new Request.Builder() .url(apiUrl) .post(body) // 对于POST请求 .build(); // 发送请求并获取响应 Response response = client.newCall(request).execute(); // 检查状态码,通常2XX表示成功 if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response.code()); } // 从响应获取响应体作为字符串 String responseBody = response.body().string(Charset.forName("UTF-8")); return responseBody; } ``` 这个函数接收API URL和一个参数映射(Map),然后发送一个POST请求。注意这里的示例假设了参数是作为一个查询字符串附加到URL上,如果是JSON格式,则需要创建一个`RequestBody`来携带JSON数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值