我正在開發一個通過HTTP調用RESTful服務器的Android應用程序。問題是,我收到以下錯誤:NegativeArraySizeException -1
。我無法弄清爲什麼問題在發生。NegativeArraySizeException -1
我有兩個類:ReadHttpTask
和HttpHelper
。該錯誤似乎是由HttpHelper類中的StringBuilder引起的,或者至少是調試器顯示異常原因的地方。
ReadHttpTask:
public class ReadHttpTask extends AsyncTask<String, Void, CharSequence> {
@Override
protected CharSequence doInBackground(String...urls) {
String urlString = urls[0];
try{
CharSequence result = HttpHelper.GetHttpResponse(urlString);
return result;
} catch (IOException ex){
cancel(true);
String errorMessage = ex.getMessage() + "\n" + urlString;
Log.e("Something went wrong", errorMessage);
return errorMessage;
}
}
}
HttpHelper:
public class HttpHelper {
public static CharSequence GetHttpResponse(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
if(!(connection instanceof HttpURLConnection)){
throw new IOException("Not an HTTP connection");
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK){
String responseMessage = httpConnection.getResponseMessage();
throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
}
InputStream inputStream = httpConnection.getInputStream();
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder(httpConnection.getContentLength());
while(true){
String line = reader.readLine();
if(line==null) break;
result.append(line);
}
return result;
} finally {
if(reader != null) reader.close();
}
}
}
你只能得到,如果你想創建一個數組'NegativeArraySizeException' - 我不能看到你這樣做,在該代碼。請包含完整的堆棧跟蹤,並在上面的代碼中指明相關的行號。 –
閱讀此:https://developer.android.com/reference/java/net/URLConnection.html#getContentLength()就像你說的,這個來自Stringbuilder接收-1。爲什麼,請檢查您用於創建此實例的方法。該文告訴你,它可能在兩種情況下返回-1。 – AxelH
@AndyTurner,StringBuilder也使用這個異常,因爲它是一個動態字符數組;) – AxelH