Android中进行基于HTTP协议的网络访问基础

本文介绍在安卓中使用HttpClient和HttpURLConnection进行HTTP网络访问的方法。详细展示了POST和GET请求的实现步骤,包括设置请求头、添加请求参数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安卓中进行基于HTTP协议的网络访问

 

两种方式:

HttpClient (apache开发)

HttpURLConnectiongoogle在发布安卓时在Java基础上修改得到的)

 

进行网络访问的基本步骤:

1. 创建HC/UC对象

2. 声明发起网络访问的方式(GET/POST)

3. 进行网络连接

4. 获得服务器响应的结果

5. 解析结果,提取需要的内容

6. 解析结果要提交到UI线程进行呈现

 

Ps:必须申请权限 INTERNET访问权限;任何网络访问的相关代码,必须在工作线程中执行!

 

一、HttpClient (apache开发)方式:

1. post提交方式

HttpClient client = new DefaultHttpClient();

HttpClient client = new DefaultHttpClient();

HttpPost post = new HttpPost("http://172.88.134.152:8080/ems/login.do");

//添加一个请求头,对请求实体中的参数做一个说明

post.setHeader("Content-Type""application/x-www-form-urlencoded");

post.setHeader("Cookie", sid);

//在post中添加请求参数,请求参数会添加在请求实体中

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("loginname", loginUser.getUserName()));

parameters.add(new BasicNameValuePair("password", loginUser.getPassword()));

parameters.add(new BasicNameValuePair("code", loginUser.getCode()));

HttpEntity entity = new UrlEncodedFormEntity(parameters);

post.setEntity(entity);

HttpResponse response = client.execute(post);

HttpEntity respEntity = response.getEntity();

String line = EntityUtils.toString(respEntity);

 2. get提交

//创建HC对象
URL url = new URL("http://172.88.134.152:8080/ems/getCode.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//声明获取方式 GET | POST
connection.setRequestMethod("GET");
connection.setDoInput(true);
//发起网络访问,获得服务器响应
connection.connect();
//解析响应的结果
InputStream is = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
//将解析结果从工作线程提交到主线程
Message.obtain(handler, 101, bitmap).sendToTarget();

二、HttpURLConnectiongoogle在发布安卓时在Java基础上修改得到的)方式:

URL url = new URL("http://172.88.134.152:8080/ems/login.do");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");//提交方式:GET | POST

connection.setDoInput(true);

connection.setDoOutput(true);

connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");

connection.setRequestProperty("Cookie", sid);

connection.connect();

//客户端提交数据

OutputStream out = connection.getOutputStream();

PrintWriter writer = new PrintWriter(out, true);

writer.print(getParams(loginUser));

writer.close();

//解析服务器响

InputStream in = connection.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line = reader.readLine();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值