1、最简单的get和post http 方式
btnGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
HttpGet request = new HttpGet("http://www.ineeke.com/android/android.php?name="+etName.getText().toString()+"&pwd="+etPwd.getText().toString());
try {
HttpResponse response = new DefaultHttpClient().execute(request);
if(response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity());
Toast.makeText(Main.this, result, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(Main.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
btnPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
HttpPost request = new HttpPost("http://www.ineeke.com/android/android.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", etName.getText().toString()));
params.add(new BasicNameValuePair("pwd", etPwd.getText().toString()));
try {
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient().execute(request);
if(response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity());
Toast.makeText(Main.this, result, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(Main.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
2、一定要记得为应用加权限,不然老失败的。
在AndroidManifest.xml加入:
<uses-permission android:name="android.permission.INTERNET" />