android - UnknownHostException 或 IllegalStateException

标签 android url networking

我正在尝试使用以下代码从我的应用程序连接到服务器:

public void buildGamesList(View view){
String url = "http://somedomain.eu/blabla";
String response = "...";
try {
    HttpGet getRequest = new HttpGet(url);
    HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(getRequest);
    response = responseToString(resp);
} catch (ClientProtocolException e1) {
    System.out.println("ClientProtocolException: " + e1.toString());
} catch (IOException e2) {
    System.out.println("IOException: " + e2.toString());
}
System.out.println("Response: " + response);
}

当点击定义如下的图像按钮时调用此方法

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1">
    <ImageButton android:src="@drawable/logo" 
        android:id="@+id/logoButton" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginTop="150dp" 
        android:layout_gravity="center" 
        android:onClick="buildGamesList"></ImageButton>      
</LinearLayout>

我遇到的问题是,如果我像上面那样写 url(带有前导 http://),我会得到 UnknowHostException,如果我跳过前导 http://,我会得到 java.lang.IllegalStateException: Target host 不能为空,也不能在参数中设置。

有人能帮我理解一下吗?

list 文件的一部分:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.jef.android"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />

<permission android:name="android.permission.INTERNET"></permission>
<uses_permission android:name="android.permission.INTERNET"></uses_permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".GamesListActivity"
            android:permission="android.permission.INTERNET"
            android:screenOrientation="portrait"
            android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SettingsActivity"

最佳答案

是否在AndroidManifest.xml中请求INTERNET权限?

关于android - UnknownHostException 或 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7902181/

相关文章:

android - 在没有GPS的情况下定位android中的当前位置

android - 在 ubuntu 中使用 Wireshark 分析 android 请求?

php - 如何获取没有模式且以 php 结尾的 URL 主机?

networking - 分布式、错误处理、复制 TB 的数据

android - 创建新 Ionic 项目时运行子过程电容器时发生错误

android - 如何在 Ubuntu 上模拟 iOS、Windows Phone 和黑莓

django - 未找到 'password_reset_confirm' 的反向。 'password_reset_confirm' 不是有效的 View 函数或模式名称

ios - 在 UIWebView 中加载请求之前修改 URL

java - Raspberry Pi 路由器上的组播

c++ - TCP 数据包有时会合并(并且延迟?)