我正在开发一个通过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