Android中网络操作的模板代码

本文详细介绍了Android中使用HttpURLConnection及HttpClient进行GET和POST请求的方法,包括连接设置、参数传递及响应处理等关键步骤。

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

Android中对于网络操作常用的有两种,即:HttpGet和HttpPost方法,因为很经常的使用,代码又是大同小异,当然很多时候会根据实际需要自行封装成框架,或者使用开源的框架,但是最基本的网络操作的代码我们还是需要要熟练的。下面记录这两种网络操作的一般代码,供开发参考:
1.使用HttpURLConnection方式发送Get请求

HttpURLConnection conn = null;
try {
   	String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
  	// https://host:port/path
  	URL url = new URL("http://10.0.2.2:8080/Server/servlet/LoginServlet?" + data);
	conn = (HttpURLConnection) url.openConnection();		// 打开连接
	conn.setRequestMethod("GET");		// 设置请求方法为Get
	conn.setConnectTimeout(1000 * 20);	// 设置连接超时时间为20秒
	conn.setReadTimeout(1000 * 10);		// 设置读取超时时间为10秒
	conn.connect();	// 连接
	int responseCode = conn.getResponseCode();	// 获得请求码
	if(responseCode == 200) {	// 响应码为200, 访问成功
		// 访问成功, 做相关处理
		// java.net.URLConnection#getInputStream 返回的数据通过输入流的方式进行获取
	}
} catch (Exception e) {
 	e.printStackTrace();
} finally {
	if(conn != null) {
 	 	conn.disconnect();	// 断开连接
	}
}

2.使用HttpURLConnection方式发送Post请求

HttpURLConnection conn = null;
try {
   	String data = "username=" + userName + "&password=" + password;
  	URL url = new URL("http://10.0.2.2:8080/Server/servlet/LoginServlet");
  	conn = (HttpURLConnection) url.openConnection();	 // 打开连接
  	conn.setRequestMethod(“POST”);		// 设置请求方法为Post
  	conn.setConnectTimeout(1000 * 5);	// 设置连接超时时间为5秒
  	conn.setReadTimeout(1000 * 5);		// 设置读取超时时间为5秒
  	conn.setDoOutput(true);		// 启用输出功能
	//根据服务器要求, 设置请求头信息.
	//conn.setRequestProperty("Content-Length", data.length() + "");
	//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	OutputStream out = conn.getOutputStream();		// 获得输出流
	out.write(data.getBytes());	// 把数据写进去
	int responseCode = conn.getResponseCode();	// 获得响应码
	if(responseCode == 200) {	// 响应码等于200, 请求成功
		// 访问成功. 做相应处理.
		// java.net.URLConnection#getInputStream 返回的数据通过输入流的方式进行获取
	}
} catch (Exception e) {
  	e.printStackTrace();
} finally {
	if(conn != null) {
  		conn.disconnect();	// 断开连接
	}
}

3.使用HttpClient方式发送Get请求

HttpClient client = null;
try {
client = new DefaultHttpClient();		// 定义一个客户端
String data = "username=" + userName + "&password=" + password;
// 定义一个get请求
HttpGet get = new HttpGet("http://10.0.2.2:8080/Server/servlet/LoginServlet?" + data);
HttpResponse response = client.execute(get);	// 开始执行请求
int statusCode = response.getStatusLine().getStatusCode();	// 获得响应码
if(statusCode == 200) {	// 响应码等于200, 请求成功
	// 请求成功, 进行相关处理.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null) {
client.getConnectionManager().shutdown();	// 断开连接.
}
}

4.使用HttpClient方式发送Post请求

HttpClient client = null;
try {
client = new DefaultHttpClient(); 	// 定义客户端
// 定义post请求
HttpPost post = new HttpPost("http://10.0.2.2:8080/Server/servlet/LoginServlet");
// 定义请求参数
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("username", userName));
parameters.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(parameters));	// 把参数添加到Post请求中
HttpResponse response = client.execute(post); 	// 执行访问
int statusCode = response.getStatusLine().getStatusCode();	// 获得响应码
if(statusCode == 200) {		// 响应码等于200, 请求成功
	// 请求成功, 处理相关业务.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null) {
client.getConnectionManager().shutdown();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

TechMix

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

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

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

打赏作者

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

抵扣说明:

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

余额充值