我正在关注这个网站http://givemepass.blogspot.hk/2011/12/http-server.html尝试使用 android 应用程序连接 PHP 服务器来获取消息。
GetServerMessage.java
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 org.apache.http.util.EntityUtils;
public class GetServerMessage {
public String stringQuery(String url){
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = httpclient.execute(method);
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
GetPhpServerMessageDemoActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class GetPhpServerMessageDemoActivity extends Activity {
/** Called when the activity is first created. */
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.text_view);
GetServerMessage message = new GetServerMessage();
String msg = message.stringQuery("http://192.168.1.88/androidtesting.php");
textView.setText("Server message is "+msg);
}
}
我试图从该站点http://uploadingit.com/file/d4632ekfpwjiupyn/GetPhpServerMessageDemo2.zip下载 Android 应用程序项目并在我的手机上运行,它的工作。但是当我开始一个新项目(Minimuim Requied SDK:API8,Target SDK:API17,编译:API17)并复制这两个java代码时。我已经添加了权限android.permission.INTERNET
,所以我不知道问题出在哪里,我只知道运行时HttpResponse response = httpclient.execute(method);
出错并返回字符串“网络问题”。