我正在創建一個需要與本地web服務器(WAMP)交互的android應用程序。 WAMP有一個PHP文件,只是回聲你好世界。此應用程序請求此頁面,但是當我運行應用程序並單擊觸發請求事件的按鈕時,在EditText上沒有打印出Helloworld的結果。以下是代碼:使用android請求本地主機中的php頁面的http請求
package com.mobilevoter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class mobilevoter extends Activity implements OnClickListener {
Button proceed;
EditText voter_number;
EditText id_number;
URLConnection conn;
BufferedReader myreader;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
proceed=(Button)findViewById(R.id.proceed_btn);
voter_number=(EditText)findViewById(R.id.editText_voternumber);
id_number=(EditText)findViewById(R.id.editText_idnumber);
proceed.setOnClickListener(this);
}
@Override
public void onClick(View src) {
if(src==proceed){
HttpClient authenticationClient= new DefaultHttpClient();
HttpPost url_post=new HttpPost("http://10.0.2.2/practice/index.php");
HttpResponse response;
try
{
response=authenticationClient.execute(url_post);
HttpEntity authenticationEntity=response.getEntity();
InputStream authenticationStream=authenticationEntity.getContent();
BufferedReader myreader=new BufferedReader(new InputStreamReader(authenticationStream));
String inputStream;
while((inputStream=myreader.readLine())!=null)
{
voter_number.setText(inputStream);
}
}
catch(Exception exception)
{
System.out.println(exception.getMessage());
}
/*finally
{
try
{
myreader.close();
}
catch(IOException ioexception)
{
System.out.println(ioexception.getMessage());
}
}*/
}
}
}
清單如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobilevoter"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".mobilevoter"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
我會很感激的幫助。感謝名單。
你試過調試過嗎? – MByD 2011-04-21 12:07:54
您是否在模擬器瀏覽器中試過了URL? – 2011-04-21 12:21:00
檢查index.php文件的輸出沒有以空行結束...... – Gero 2011-04-21 20:24:31