我想使用AsyncTask和默認Http客戶端訪問位於Web服務器上的PHP文件。使用HTTP訪問Web服務器Android
我不斷收到此錯誤:
無法解析主機「主機名」:沒有與主機名
相關地址這是我的活動,我嘗試訪問它:
public class MainActivity extends Activity {
Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new HTTPTask().execute();
}
});
}
private class HTTPTask extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... params) {
//location of file to retrieve
String url = "http://hostname/12345/db_connect.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return true;
}catch(Exception e){
Log.e("log_tag", "Error in Connection " + e.toString());
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result){
Toast.makeText(getApplicationContext(), "Connection Established!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Connection Failed!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "Connection initiating...", Toast.LENGTH_SHORT).show();
}
}
}
我還在清單文件中添加了以下內容:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我只是想不出它會是什麼?我在我的大學工作了一臺機器,我猜這可能是建築物的安全?任何幫助深表感謝!
清單:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dbconnectiontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
在這裏添加您的完整清單文件 –