打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
android 中okhttp post请求传递json数据

 

 


client 基础配置

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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

    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);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

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);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

调用:

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();
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java获取用户ip
微信小微商户/特约商户进件V3版本对接
AJAX传值(精)
JSON
一起学Android之Xml与Json解析
httpclient 多线程高并发Get请求
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服