Http:超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。HTTP是一个客户端和服务器端请求和应答的标准(TCP)。客户端是终端用户,服务器端是网站。通过使用Web浏览器、网络爬虫或者其它的工具,客户端发起一个到服务器上指定端口(默认端口为80)的HTTP请求。
在Android上发送HTTP请求的方式一般有两种,HttpURLConnection和HttpClient,其中后者谷歌官方已经不推荐使用,基本步骤如下:
1.申请权限INTERNET访问权限
2.任何网络访问的相关代码,必须在工作线程中执行
3.创建HttpClient/HttpURLConnection对象
4.进行网络链接
5.获得服务器响应结果
6.解析结果,提取需要的内容
7.解析结果要提交到UI线程进行呈现
对于第二部网络在工作线程访问相关代码我们可以new Thread 或者 直接利用AsyncTask
先拿HttpURLConnection为例:
首先需要获取到HttpURLConnection的实例,一般只需new 出一个URL对象,并传入目标网络的地址,然后
调用一下openConnection()方法即可,如下所示:
URL URL=new URL("http://xxxxxx");
HttpURLConnection connection=( HttpURLConnection)url.openConnection();
得到了 HttpURLConnection的实例之后,我们可以设置一下HTTP请求所使用的方法。常用的方法主要有两个,
GET和POST。GET表示希望从服务器那里获取数据,而POST则表示提交数据给服务器。写法如下:
connection.setRequestMethod("POST");注意:利用HttpClient的POST方式发起带参数的请求
利用POST方式发起请求,参数要放到请求实体中,并且在请求头中添加对实体中参数的说明。
添加说明:
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
相关代码示例:
public class EmsUtil {
public static void registUser(Context context, final User user,
final OnRegistFinishListener listener) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.60.50.82:8080/ems/regist.do");
//添加一个请求头,对请求实体中的参数做一个说明
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//在post中添加请求参数
//请求参数会添加在请求实体中
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", user.getName()));
parameters.add(new BasicNameValuePair("password", user.getPassword()));
parameters.add(new BasicNameValuePair("realname", user.getRealname()));
parameters.add(new BasicNameValuePair("email", user.getEmail()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
HttpResponse resp = client.execute(post);
HttpEntity respEntity = resp.getEntity();
String line = EntityUtils.toString(respEntity);
return line;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
listener.onRegistFinish(result);
};
}.execute();
}
public static void registUser2(Context context,final User user, final OnRegistFinishListener listener){
//HttpURLConnection进行注册
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/regist.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);//接收服务器响应的内容
connection.setDoOutput(true);//要向服务器提交内容
//在请求头中,为请求实体中的内容做说明
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
//客户端向服务器提交参数
OutputStream out = connection.getOutputStream();
PrintWriter pw = new PrintWriter(out, true);
String params = getParams(user);
pw.print(params);
pw.close();
//客户端获取服务器的响应内容
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
//在主线程执行
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
listener.onRegistFinish(result);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
protected static String getParams(User user) {
Map<String,String> map = new HashMap<String, String>();
map.put("loginname", user.getName());
map.put("password", user.getPassword());
map.put("realname", user.getRealname());
map.put("email", user.getEmail());
StringBuilder sb = new StringBuilder();
for(Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey()).
append("=").
append(entry.getValue()).
append("&");
}
return sb.substring(0, sb.length()-1);
}
以上的两个方法为我在之前做过项目中截取的两个部分,他们分别用new Thread 搭配 HttpURLConnection以及
AsyncTask搭配HttpClient实现了相同的功能,以供参考。(未完待续)