0
我知道還有一個這樣的帖子,但它沒有幫助。android http請求在設備上不起作用,在仿真器工程中
我的代碼是在模擬器,但在設備上工作,我得到一個異常: java.lang.IllegalArgumentException異常:主機名不能爲null
權限設置:
<uses-permission android:name="android.permission.INTERNET" />
這裏是代碼:
package com.example.testapp;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
public class mainAct extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ARequestTask task = new ARequestTask();
task.execute(new String[] {});
}
class ARequestTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String hallo = "test";
Log.d("EMAIL", hallo);
try {
HttpClient client = new DefaultHttpClient();
URI uri = new URI("http://.../android/index.php");
HttpGet get = new HttpGet(uri);
HttpResponse responseGET = client.execute(get);
HttpEntity resEntity = responseGET.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// use the result as you wish
}
}
}
每次HttpGet將被執行時,異常出現,但只在設備上。
看到錯誤是如何報告主機名的,您可能不想在示例代碼中混淆主機名。或者您的主機名稱是「...」? –
此外,只需將主機名字符串直接放入HttpGet構造函數即可。 'HttpGet get = new HttpGet(「http://.../android/index.php」);' – varevarao