[英]Getting error when using HttpUrlConnection with Android compiling against SDK 21
我找到了問題,根本不在我發布的代碼中。 mulTi線程的風險,以及最近切換到Android Studio的風險。 SDK 21中的菜單存在問題,並且我沒有使用指南來切換為使用Android 5.0主題和ActionBar。
我在使用HttpUrlConnection時遇到問題。 我用它來調用用PHP編寫的api。 該應用程序下載有關啟動的文章摘要,並且效果很好。 當您單擊某篇文章時,它將下載該文章的其余信息,並在新活動中顯示該信息。 至少應該認為它現在已經可以在您單擊摘要時開始崩潰。 在以下代碼中到達conn.connect行時崩潰
public String downloadUrl(String myurl) throws IOException {
InputStream is = null;
HttpURLConnection conn=null;
String contentAsString=null;
try {
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setInstanceFollowRedirects(true);
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("HttpReader", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
conn.disconnect();
if (is != null) {
is.close();
}
}
return contentAsString;
}
我已將錯誤跟蹤到文件Choreographer.java和以下函數
void doCallbacks(int callbackType, long frameTimeNanos) {
CallbackRecord callbacks;
synchronized (mLock) {
// We use "now" to determine when callbacks become due because it's possible
// for earlier processing phases in a frame to post callbacks that should run
// in a following phase, such as an input event that causes an animation to start.
final long now = SystemClock.uptimeMillis();
callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked(now);
if (callbacks == null) {
return;
}
mCallbacksRunning = true;
}
try {
for (CallbackRecord c = callbacks; c != null; c = c.next) {
if (DEBUG) {
Log.d(TAG, "RunCallback: type=" + callbackType
+ ", action=" + c.action + ", token=" + c.token
+ ", latencyMillis=" + (SystemClock.uptimeMillis() - c.dueTime));
}
c.run(frameTimeNanos);
}
} finally {
synchronized (mLock) {
mCallbacksRunning = false;
do {
final CallbackRecord next = callbacks.next;
recycleCallbackLocked(callbacks);
callbacks = next;
} while (callbacks != null);
}
}
}
在finally子句callbacks中將引發空指針異常。next提供一個NullPtrException。
我已經測試了我在Chrome中使用的url,它重新運行了應該使用的JSON,並且還使用curl進行了測試,再次得到了我期望的JSON。
我不確定是怎么了。
我不認為您可以在主線程上運行它-您需要使用AsyncTask對其進行包裝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.