【问题标题】:A simple http request on android, no idea why get errorandroid上一个简单的http请求,不知道为什么会出错
【发布时间】:2012-03-21 11:48:49
【问题描述】:

这是一个简单的获取请求

我发现异常是由

引起的
"HttpResponse response = client.execute(request);"

我不知道为什么,因为它是从示例中复制的。

我尝试了不同的网址,但仍然得到异常

如果我打印异常,我会得到空指针异常

现在我不知道如何找出问题

谁知道这个问题的原因是什么?

这里是这个问题的视频link -

public void onClick(View view) {
    String url = "http://www.google.com";
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
    } catch (Exception e) {
        //Log.v("cc",e.getMessage());
        Log.v("dd", "error");
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="so.lab4"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/> 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Lab4Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【问题讨论】:

  • 您应该使用Log.v("dd", e) 来查看异常。
  • 或者更好的打印backstack
  • 或使用 Log.v("dd", e.printStackTrace());
  • 代码看起来没问题,并且添加了inet权限。但是你永远不应该从你的 UI 线程发出 HTTP 请求。使用 Handler 或 AsyncTask
  • Log.v("dd", e)Log.v("dd", e.printStackTrace()),它们也不起作用,因为它只接受字符串参数,现在我使用 Log。 v("dd", e.toString()) 并获取 NetworkOnMainThreadException

标签: java android sdk get httprequest


【解决方案1】:

在事件线程中建立 HTTP 连接太糟糕了!

您应该在工作线程中完成此类工作。如果没有,您将暂停事件线程处理 GUI 事件,并且如果线程保持超过 5 秒,它将抛出一个很好的 ANR(AKA 应用程序无响应)错误。

【讨论】:

  • 目前我发现这个可以解决问题,我将使用工作线程来处理它。 code StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build());
  • 好的,但请记住,StrictMode 不能保证在主线程中找到您做错的所有事情,并且有时会警告绝对正常的事情。它只能从 Gingerbread 开始使用,并且只能在调试版本中使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多