在针对SDK 21的Android编译中使用HttpUrlConnection时出错

时间:2014-11-29 18:59:51

标签: java android httpurlconnection

我找到了问题,它不在我发布的代码中。 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中使用的网址,它重新测试了它应该使用的JSON,并且还使用curl进行了测试,我再次得到了我期望的JSON。

我不确定是什么问题。

1 个答案:

答案 0 :(得分:0)

我不认为你可以在主线程上运行它 - 你需要用AsyncTask包装它。