我正在尝试使用 AsyncTask 和默认 Http 客户端访问位于 Web 服务器上的 php 文件。
我不断收到此错误:
无法解析主机“主机名”:没有与主机名关联的地址
这是我尝试访问它的活动:
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>