Android的网络请求方式解析

本文提供了HTTP GET和POST请求的具体实现示例,包括如何建立连接、设置超时时间、发送请求参数以及处理响应数据。

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

Get方式:

// Get方式请求  
02.public static void doGet() throws Exception {  
03.    String path = "http://203.156.252.170:8008/logins?username=liu&pwd=123456";  
04.    // 新建一个URL对象  
05.    URL url = new URL(path);  
06.    // 打开一个HttpURLConnection连接  
07.    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
08.    // 设置连接超时时间  
09.    urlConn.setConnectTimeout(3* 1000);  
10.    // 开始连接  
11.    urlConn.connect();  
12.    // 判断请求是否成功  
13.    if (urlConn.getResponseCode() == 200) {  
14.        // 获取返回的数据  
15.        byte[] data = readStream(urlConn.getInputStream());  
17.        Log.i(TAG_GET, new String(data, "UTF-8"));  
18.    } else {  
19.        Log.i(TAG_GET, "Get方式请求失败");  
20.    }  
21.    // 关闭连接  
22.    urlConn.disconnect();  
23.}  

Post方式:

// Post方式请求  
02.public static void doPost() throws Throwable {  
03.    String path = "http://203.156.252.170:8008/logins";  
04.    // 请求的参数转换为byte数组  
05.    String params = "username=" + URLEncoder.encode("liu", "UTF-8")  
06.            + "&pwd=" + URLEncoder.encode("123456", "UTF-8");  
07.    byte[] postData = params.getBytes();  
08.    // 新建一个URL对象  
09.    URL url = new URL(path);  
10.    // 打开一个HttpURLConnection连接  
11.    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
12.    // 设置连接超时时间  
13.    urlConn.setConnectTimeout(3 * 1000);  
14.    // Post请求必须设置允许输出  
15.    urlConn.setDoOutput(true);  
16.    // Post请求不能使用缓存  
17.    urlConn.setUseCaches(false);  
18.    // 设置为Post请求  
19.    urlConn.setRequestMethod("POST");  
20.    urlConn.setInstanceFollowRedirects(true);  
21.    // 配置请求Content-Type  
22.    urlConn.setRequestProperty("Content-Type",  
23.            "application/x-www-form-urlencode");  
24.    // 开始连接  
25.    urlConn.connect();  
26.    // 发送请求参数  
27.    DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
28.    dos.write(postData);  
29.    dos.flush();  
30.    dos.close();  
31.    // 判断请求是否成功  
32.    if (urlConn.getResponseCode() == 200) {  
33.        // 获取返回的数据  
34.        byte[] data = readStream(urlConn.getInputStream());  
35.        Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");  
36.        Log.i(TAG_POST, new String(data, "UTF-8"));  
37.    } else {  
38.        Log.i(TAG_POST, "Post方式请求失败");  
39.    }  
40.}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是宇哥啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值