android - OkHttp庫使用如何完整的獲取json數據
問題描述
在使用Okhttp中,獲取json數據時,發現獲取的數據不完全。服務器文件
使用okhttp請求test2.json(59KB)
···
OkHttpClient client = new OkHttpClient(); Request request=new Request.Builder().get().url('http://192.168.31.207/test2.json').build(); client.newCall(request).enqueue(new getCallBack());
···
getCallBack()為implements Callback(okhttp包下的)的類
重寫成功的回調方法···
public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){//String line ;//BufferedReader br = new BufferedReader(new InputStreamReader(response.body().byteStream()));//while ((line=br.readLine())!=null){// L.e(line);//}Reader r = response.body().charStream();char[] B = new char[4096];int length;while ((length=r.read(B))>0){ L.e(String.valueOf(B));}r.read(B); }}
···
無論是用byteStream還是用reader 都不能獲取完整數據把char數組換成更大100000+也無濟于事
打印的數據殘缺。
但是將請求換成test.html(254KB)時又能全部輸出
請問如何能成功的獲取json數據?
問題解答
回答1:@Overridepublic void onResponse(Response response) { if (response.isSuccessful()) {try { final String result = response.body().string(); if (!TextUtils.isEmpty(result)) {JSONObject obj = new JSONObject(result);// 解析資料 }} catch (Exception e) { Log.e(TAG, 'Exception = ' + e);} }}回答2:
通過測試發現,控制行打印的數據有長度限制,并不會將所有的輸出進行打印。但是數據是完整的。
回答3:因為android studio的logcat中一次打印的數據有4M(4*1024k)的顯示,所以,如果json中的數據太多,在android studio的logcat中是顯示不完全的,如果想款看全部日志,需要把日志導出來查看。這里推薦一種使用notepad++查看的方式:https://zhuanlan.zhihu.com/p/...
相關文章:
