我尝试从我的网络/http://localhost/android_connection/getHttpGet.php
获取数据,该数据遵循此网站的代码http://www.thaicreate.com/mobile/android-httpget-httppost.html。
在此行之后的“/http://localhost/android_connection/getHttpGet.php
”结果:
Server Date/Time : 2014-06-04 04:28:49
我正在使用Xampp作为我的localhost。
在android编程中 >>之后的代码HttpResponse response = client.execute(httpGet)不会通过捕获log.e来运行。 Log.e(“error1.1”,“before try”);和Log.e(“error1.2”,“在HttpResponse之前”);只出现在我的LogCat上。
我不知道如何修复plz帮助我,顺便说一句我是通过Android应用程序使用webserver进行编程的初学者。
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final TextView result = (TextView) findViewById(R.id.result);
final Button btnGet = (Button) findViewById(R.id.btnGet);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String url = "http://localhost/android_connection/getHttpGet.php";
String resultServer = getHttpGet(url);
result.setText(resultServer);
}
});
}
public String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.e("error1.1","Before try");
try {
Log.e("error1.2", "Before HttpResponse");
HttpResponse response = client.execute(httpGet);
Log.e("error1.3", "End of HttpResponse");
StatusLine statusline = response.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
Log.e("error2","line : " + line);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str.toString();
}
}
答案 0 :(得分:1)
问题在于您的服务器网址,Android设备无法识别localhost网址,因为这是您的机器网址。我个人建议您通过机器IP访问XAMP服务器,但如果您正在使用模拟器并且想要使用本地主机,则只需将URL更改为10.0.2.2。请参阅developer guide