Android API错误/ httpget NetworkOnMainThreadException

时间:2014-08-17 06:14:16

标签: android http-get

这是我的错误消息:

08-17 07:58:14.286 32620-32620 / xxx.dk.xxx E / AndroidRuntime:FATAL EXCEPTION:main     处理:xxx.dk.xxx,PID:32620     android.os.NetworkOnMainThreadException             在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239)             at java.net.InetAddress.lookupHostByName(InetAddress.java:388)             at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)             at java.net.InetAddress.getAllByName(InetAddress.java:214)             在com.android.okhttp.internal.Dns $ 1.getAllByName(Dns.java:28)             在com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)             在com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)             在com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)             在com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)             在com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)             在com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)             在com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)             at xxx.dk.xxx.DAL.JsonConnection.checkSecret(JsonConnection.java:42)             at xxx.dk.xxx.BLL.CheckCarrierData.checkSecret(CheckCarrierData.java:14)             在xxx.dk.xxx.GUI.Login.onClick(Login.java:49)             在android.view.View.performClick(View.java:4480)             在android.view.View $ PerformClick.run(View.java:18686)             在android.os.Handler.handleCallback(Handler.java:733)             在android.os.Handler.dispatchMessage(Handler.java:95)             在android.os.Looper.loop(Looper.java:157)             在android.app.ActivityThread.main(ActivityThread.java:5872)             at java.lang.reflect.Method.invokeNative(Native Method)             在java.lang.reflect.Method.invoke(Method.java:515)             在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:858)             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)             在dalvik.system.NativeStart.main(本地方法)

我试图使用httpGet方法,该方法正在使用API​​10,但是当我在4.4.2的单元上使用它时失败 - >我需要API10及以上的支持。

代码:

public class JsonConnection
{
private String secretJsonStr = null;
private String nameOfCarrier = "";
public String checkSecret(String secret)
{
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;



    final String QueryParam = "secret";

    try
    {
        final String httpUrl = "***SOMEURL***?";

        Uri builtUri = Uri.parse(httpUrl).buildUpon().
appendQueryParameter(QueryParam, secret.toString()).build();

        URL url = new URL(builtUri.toString());

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
        {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null)
        {
            buffer.append(line + "\n");
        }
        if (buffer.length() == 0)
        {
            // Stream was empty. No point in parsing.
            return null;
        }
        secretJsonStr = buffer.toString();
    } catch (IOException e)
    {
        Log.e("Login", "Error", e);
        return null;
    } finally
    {
        if (urlConnection != null)
        {
            urlConnection.disconnect();
        }
        if (reader != null)
        {
            try
            {
                reader.close();
            } catch (final IOException e)
            {
                Log.e("Login", "Error closing stream", e);
            }
        }
    }
    try
    {
        JSONObject secretJson = new JSONObject(secretJsonStr);
        nameOfCarrier = getCarrierInfoFromJson(secretJson);

    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    return nameOfCarrier;
}

private String getCarrierInfoFromJson(JSONObject secretJson)
        throws JSONException
{

    final String CARRIER_NAME = "Name";

    String nameOfCarrier2 = secretJson.getString(CARRIER_NAME);

    return nameOfCarrier2;


    }
}

由于一些保护,我无法向您显示URL,但在API 10 2.3.6单元中运行时,一切都像魅力一样..

我可以在所有Android设备上完全向后兼容。

希望你有知识帮助我,我肯定看不出怎么样。 : - (

最诚挚的问候 拉斯穆斯

3 个答案:

答案 0 :(得分:0)

问题是http请求是在主线程(NetworkOnMainThreadException)上执行的,因此您需要将调用移到Thread。更多信息here

更新:实际上,可能是this的重复。

答案 1 :(得分:0)

由于错误,您无法在MainThread上执行会冻结屏幕的HTTP连接。这是不合适的。

您可以获得以下权限:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

但是,这不是一个好习惯。您必须在后台线程上运行http连接并向用户显示加载消息。

new Thread(new Runnable() {
            @Override
            public void run() {
                // code goes here ...
            }
        }).start();

答案 2 :(得分:0)

正如其他答案所暗示的那样,您收到此错误是因为您正在主线程上运行网络操作。我建议使用AsyncTask。

This link显示了AsyncTask的结构。

要调用AsyncTask,请使用

//getData() is name of class
new getData().execute();

有关Android Developer site的更多参考资料。