安卓使用HttpURLConnection以get方式请求数据

该博客详细介绍了如何在安卓应用中使用HttpURLConnection进行GET请求数据的步骤,包括实例化URL对象、设置请求方式、获取输入流并转换为字符串,同时提醒注意需要在AndroidManifest.xml中添加联网权限并在子线程执行以避免主线程网络操作异常。
摘要由CSDN通过智能技术生成

1、实例化URL对象

URL url = new URL("https://www.baidu.com/s?ie=UTF-8&wd=get");

2、通过URL对象打开链接获取HttpURLConnection的实例化对象

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

3、设置请求方式

conn.setRequestMethod("GET");

4、通过HttpURLConnection对象获取输入流

 InputStream is = conn.getInputStream();

5、将输入流转换成String类型

//把一个inputStream 转换成一个String
public String inputStreamToString(InputStream is) throws Exception{
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	int len = -1;
	byte[] buffer = new byte[1024]; 
	while((len=is.read(buffer))!=-1){
	    baos.write(buffer, 0, len);
	}
	is.close();
	String content = new String(baos.toByteArray());
	return content;
}


String result = inputStreamToString(is);

或者使用BufferReader类转换

BufferedReader r
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值