使用okhttp时没有返回json数据

来源:互联网 发布:淘宝淘金币兑换区 编辑:程序博客网 时间:2024/05/21 15:03

转自 http://m.blog.csdn.net/article/details?id=51898106

今天踩过的大坑........

这是一段使用okhttp进行post请求的代码


 OkHttpClient client = new OkHttpClient();        RequestBody body = new FormEncodingBuilder()                .add("key", value)                .build();        Request request = new Request.Builder()                .url(urlstr)                .post(body)                .build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Request request, IOException e) {            }            @Override            public void onResponse(Response response) throws IOException {                final String res = response.body().string();                new Thread(new Runnable() {                    @Override                    public void run() {                        Log.d("response", res);                    }                }).start();            }        });

运行结果返回的是com.squareup.okhttp.internal.http.RealResponseBody@52858c28这段字符串,一脸懵逼,本来应该是返回一段json字符串的。

解决方法:

Replace

String json = response.body().toString();

with

String json = response.body().string();

改了之后运行一下就出来了:

{"code":1,"msg":"成功","result":"201607121644019558"}





0 0