Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE,分别对应查,改,增,删四种操作。Android中最常用的是HttpGet和HttpPost
无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。
1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。、
HttpGet方法
public String doGet()
{
String uriAPI = "http://192.168.1.1/index.php/?name=jason&password=1234";
String result= "";
// 创建HttpGet对象,将要请求的URL通过构造方法传入,参数附在url的后面。
HttpGet httpRequst = new HttpGet(uriAPI);
try {
// 使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子类
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出应答字符串
}
else
httpRequst.abort();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
HttpPost方法
如果使用HttpPost方法提交HTTP POST请求,则需要使用HttpPost类的setEntity方法设置请求参数。参数则必须用NameValuePair[]数组存储。
public String doPost()
{
String uriAPI = "http://192.168.1.1/index.php";//Post方式没有参数在这里
String result = "";
HttpPost httpRequst = new HttpPost(uriAPI);//创建HttpPost对象
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "jason"));
params.add(new BasicNameValuePair("password", "1234"));
try {
httpRequst.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出应答字符串
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
原理:android客户端通过HttpPost发送用户名和密码到服务器端,服务器端收到数据,连接到数据库查询,如果匹配正确,就输出login succeed返回给客户端
服务器端:
在mysql中新件testConnect数据库,创建users表
新建php项目,建立文件login.php
<?php
$dbhost="localhost:3306