在项目中碰到上传log功能,log是以json形式存在,所以需要一个上传json数据的网络请求,使用的是okhttp,非常方便
OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8") , json); Request request = new Request.Builder() .url(url)//请求的url .post(requestBody) .build(); okhttp3.Call call = okHttpClient.newCall(request); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { final String res = response.body().string(); if (response.code() == 200) { Log.i(TAG, "成功"); } } });