我正在使用 Okhttp3 获取 Json 数据。我发布了两个参数,作为响应应该给我 Json 数据。调用了 onResponse 方法,但我得到的响应是“okhttp3.internal.http.RealResponseBody@21e14bf0”而不是 Json。这是我第一次使用 Okhttp。请查看以下代码:
代码:
String url="http://xxxxx.com/data.php";
OkHttpClient okHttpClient=new OkHttpClient();
RequestBody requestbody=new FormBody.Builder().add("name",usr_nme).add("date",date).build();
Request request=new Request.Builder().url(url).post(requestbody).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
progressDialog.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
progressDialog.cancel();
throw new IOException("Unexpected code " + response);
} else {
// do something wih the result
Log.e("Response",response.body().toString());
progressDialog.cancel();
try {
JSONObject jsonObject=new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
异常(已编辑):
:
{"user_details":{"numeron_user":[{"nme_nmbr":1,"details":"The 1 is a doer, a powerful force"},{"lfepth_nmbr":8,"details":"You are strong tough and can be ruthless. You enjoy continuous hassles and struggle for power."},{"day_nmbr":4,"details":"Number 4 resonates with the vibrations and energies of practicality, organization and exactitude"},{"more_info":"If birth or lifepath number is 4 or 8 the name number should be in the vibration of 1,3,5,6. Change your name so that it produces the vibration of the previously said numbers. Never increase the vibration of 4 or 8 in your life.\r\n\r\nFor selecting a mobile phone number make sure the number adds up to 1,3,5 or 6."}]}}
10-24 15:30:16.681 6974-7502/com.root5solutions.numerology E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.root5solutions.numerology, PID: 6974
java.lang.IllegalStateException: closed
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392)
at okhttp3.internal.Util.bomAwareCharset(Util.java:449)
at okhttp3.ResponseBody.string(ResponseBody.java:174)
at com.root5solutions.numerology.UserInput$BackgroundTask$1.onResponse(UserInput.java:118)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
10-24 15:30:16.791 6974-6974/com.root5solutions.numerology E/ViewRootImpl: sendUserActionEvent() mView == null
最佳答案
将 response.body().toString()
更改为 response.body().string()
。
关于android - OkHttp 响应不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46907229/