android Okhttp3进行JSON类型请求的封装

 使用插件:okhttp-3.10.0和okio-1.14.0

    //TOKEN
    public static String TOKEN = "";
    //请求端口号
    public final static String address = "http://127.0.0.1:7001";
    //转换Map类型为JSON对象类型
    public static String JSONStringify(Map<String,Object> body){
        StringBuilder jsonBody = new StringBuilder("{");
        for (Object entry : body.entrySet()){
            Map.Entry m = (Map.Entry) entry;
            if (m.getValue() instanceof List)
                jsonBody.append("\""+m.getKey()+"\":"+JSONStringify((List<Object>) m.getValue()));
            if (m.getValue() instanceof Map)
                jsonBody.append("\""+m.getKey()+"\":"+JSONStringify((Map<String, Object>) m.getValue()));
            if (m.getValue() instanceof Integer)
                jsonBody.append("\""+m.getKey()+"\":"+m.getValue());
            if (m.getValue() instanceof String)
                jsonBody.append("\""+m.getKey()+"\":"+"\""+m.getValue()+"\"");
            jsonBody.append(",");
        }
        int index = jsonBody.lastIndexOf(",");
        if (index != -1)jsonBody.delete(index,index+1);
        jsonBody.append("}");
        return jsonBody.toString();
    }

    //转换List类型为JSON数组类型
    public static String JSONStringify(List<Object> list){
        StringBuilder jsonBody = new StringBuilder("[");
        for (Object item : list){
            if (item instanceof Map)
                jsonBody.append(JSONStringify((Map<String, Object>) item));
            if (item instanceof Integer)
                jsonBody.append(item);
            if (item instanceof String)
                jsonBody.append("\""+item+"\"");
            if (item instanceof List)
                jsonBody.append(JSONStringify((List<Object>) item));
            jsonBody.append(",");
        }
        int index = jsonBody.lastIndexOf(",");
        if (index != -1)jsonBody.delete(index,index+1);
        jsonBody.append("]");
        return jsonBody.toString();
    }

    //post请求,body不传参则传{}
    public static void post(String url, String body, Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"),body);
        Request request = new Request.Builder()
                        .url(address+url)
                        .addHeader("Authorization",TOKEN)
                        .post(requestBody)
                        .build();
        client.newCall(request).enqueue(callback);
    }

    //put请求
    public static void put(String url, String body, Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = 
            RequestBody.create( MediaType.parse("application/json; charset=utf-8"),body);
        Request request = new Request.Builder()
                .url(address+url)
                .addHeader("Authorization",TOKEN)
                .put(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }

    //get请求,不传参数则传null
    //传参示范:"/1" "?name='1'"
    // 也可以直接写在url中,传参传null或""
    public static void get(String url, String body, Callback callback){
        if (body != null){
            url += body;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address+url)
                .addHeader("Authorization",TOKEN)
                .get()
                .build();
        client.newCall(request).enqueue(callback);
    }
    
    //delete请求,不传参数则传null
    // 传参示范:"/1"
    // 也可以直接写在url中,传参传null或""
    public static void delete(String url, String body, Callback callback){
        if (body != null){
            url += body;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address+url)
                .addHeader("Authorization",TOKEN)
                .delete()
                .build();
        client.newCall(request).enqueue(callback);
    }

请求参考:

//将传递数据放入Map中
Map<String,Object> data = new HashMap<>();
data.put("username","admin");
data.put("password","123456");

//OkhttpUtil为上面代码的封装类
//实现okhttp3的Callback方法
OkhttpUtil.post("/login", OkhttpUtil.JSONStringify(data), new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e("request",e.getLocalizedMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String data = response.body().string();
        //存储token
        try {
            JSONObject jsonObject = new JSONObject(data);
            OkhttpUtil.TOKEN = jsonObject.getString("token");
        } catch (Exception e) {
            Log.e("request",e.getLocalizedMessage());
        }
        Log.d("request",data);
    }
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
封装一个包含 Header、Cookie 和 Data 的 Post 请求,你可以使用 Android 系统自带的 HttpURLConnection 类或者第三方库 OkHttp。 以下是使用 HttpURLConnection 封装 Post 请求的示例代码: ```java public static String post(String urlString, String data, Map<String, String> headers, String cookie) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setDoOutput(true); conn.setDoInput(true); // 设置 Header if (headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> entry : headers.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } // 设置 Cookie if (cookie != null && !cookie.isEmpty()) { conn.setRequestProperty("Cookie", cookie); } // 写入请求数据 OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); // 读取响应数据 InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); is.close(); conn.disconnect(); return response.toString(); } ``` 使用该方法时,需要传入以下参数: - urlString:请求的 URL 地址; - data:请求的数据,可以是 JSON 字符串等; - headers:请求的 Header,可以为空; - cookie:请求的 Cookie,可以为空。 示例代码中使用了字节流和字符流进行数据的写入和读取,可以根据实际情况选择使用哪种方式。 如果你使用 OkHttp 库来进行网络请求,也可以类似的方式设置 Header、Cookie 和请求数据。以下是使用 OkHttp封装 Post 请求的示例代码: ```java public static String post(String urlString, String data, Map<String, String> headers, String cookie) throws IOException { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), data); Request.Builder builder = new Request.Builder() .url(urlString) .post(requestBody); // 设置 Header if (headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> entry : headers.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } // 设置 Cookie if (cookie != null && !cookie.isEmpty()) { builder.addHeader("Cookie", cookie); } Request request = builder.build(); Response response = client.newCall(request).execute(); String result = response.body().string(); response.close(); return result; } ``` 使用该方法时,需要传入以下参数: - urlString:请求的 URL 地址; - data:请求的数据,可以是 JSON 字符串等; - headers:请求的 Header,可以为空; - cookie:请求的 Cookie,可以为空。 示例代码中使用了 OkHttp 库的 RequestBody 和 Request.Builder 类来设置请求数据和 Header,也可以根据实际情况选择使用其他方式设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值