[英]getContentLength() returning -1 on some devices and not others
[英]getContentLength returning 1225, real length 3365
我目前正在使用android,並且正在使用帶有某些標頭的http連接(出於安全目的,我沒有包括它們或真實的url)來從API獲取JSON響應,並將該響應反饋給應用程序。 我遇到的問題是,當使用http請求的getContentLength方法時,返回了錯誤的長度(返回的錯誤長度是1225,JSON數組中字符的正確長度是3365)。
我有一種感覺,當我的閱讀器開始讀取JSON時,JSON尚未完全加載,因此僅在那時讀取已加載的JSON。 有什么辦法解決這個問題,可能是在HTTP連接上使用了延遲,或者是等到它完全加載以讀取數據之后?
URL url = new URL("https://www.exampleofurl.com");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
int responseCode = request.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = request.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
long contentLength2 = Long.parseLong(request.getHeaderField("Content-Length"));
Log.i("contentLength: ", "Content: " + contentLength2);
我通常不建議總是依賴“ Content-Length”,因為它可能不可用(您得到-1),或者可能受中間代理的影響。
為什么不讀流直到將其用盡到內存緩沖區(例如StringBuilder
)中,然后獲取實際大小,例如:
BufferedReader br = new BufferedReader(inputStream); // inputStream in your code
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
// finished reading
System.out.println("data size = " + sb.length());
JSONObject data = new JSONObject(sb.toString());
// and don't forget finally clauses with closing streams/connections
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.