最新消息:网站改版咯

android实现HTTP通信

移动App Yovae 1244浏览

android程序HTTP通信的简单示例。这里用一个最简单的登录验证开始,数据的提交方式分别使用GET和POST,利用Toast来提示登录结果。

android http get and postandroid http get and post

android.php源码:

<?php
$REQUEST_METHOD = $_SERVER['REQUEST_METHOD'];
echo $REQUEST_METHOD;
if($REQUEST_METHOD == 'GET'){
$name = $_GET['name'];
$pwd = $_GET['pwd'];

if($name == 'Neeke' && $pwd == 'Neeke'){
echo '你好:'.$name;
}else{
echo '登录失败!';
}
}else if($REQUEST_METHOD == 'POST'){
$name = $_POST['name'];
$pwd = $_POST['pwd'];

if($name == 'Neeke' && $pwd == 'Neeke'){
echo '你好:'.$name;
}else{
echo '登录失败!';
}
}

?>

android主程序源码:

public class Main extends Activity {

private Button btnGet;
private Button btnPost;
private EditText etName;
private EditText etPwd;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnGet = (Button) findViewById(R.id.btnGet);
btnPost = (Button) findViewById(R.id.btnPost);
etName = (EditText) findViewById(R.id.etName);
etPwd = (EditText) findViewById(R.id.etPassword);

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 params = new ArrayList();
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();
}
}
});
}
}

 

android实现HTTP通信切记不要忘记要赋予程序访问网络的权限!。
在AndroidManifest.xml加入:

<uses-permission android:name=”android.permission.INTERNET” />

转载请注明:Yovae Studio » android实现HTTP通信