首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >android-中okhttp-传递json数据

android-中okhttp-传递json数据

作者头像
tea9
发布2022-07-16 15:31:42
发布2022-07-16 15:31:42
9730
举报
文章被收录于专栏:tea9的博客tea9的博客

参考地址 http://blog.csdn.net/lmj623565791/article/details/47911083 client 基础配置

代码语言:javascript
复制
public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
public static final OkHttpClient client = new OkHttpClient.Builder()
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
        .build();

get方法 参数: url get请求地址

代码语言:javascript
复制
    public String get(String url) throws IOException {
    Request request = new Request.Builder().url(url).get().build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

post方法 参数: url post请求地址 json json字符串

代码语言:javascript
复制
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

public static String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

调用:

代码语言:javascript
复制
new Thread() {
    @Override
    public void run() {
        //传的json
        JSONObject jsonObject = new JSONObject();
        try {
            String callStr = OKHttpTool.post(HttpUrl.API_ACTIVE, jsonObject.toString());
            JSONObject call_json = new JSONObject(callStr);
            final String msg = call_json.getString("msg");
            if (call_json.getInt("status") == 1){
                //在子线程中调用ui线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ActivationCardActivity.this, msg, Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}.start();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档