安卓中进行基于Http协议的网络访问基础总结-1

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实现了相同的功能,以供参考。(未完待续)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值