我正在尝试使用以下代码从我的应用程序连接到服务器:
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/