HttpURLConnection解析网络数据

1.首先价绍一下他是java自带的网络请求数据的方法,必须在线程里执行。

<pre name="code" class="java">try {
			// 设置要访问地址
			URL url = new URL(path);
			// 打开连接,得到HttpURLConnection对象
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			// 设置联网超时
			connection.setConnectTimeout(5000);
			// 设置请求方式
			connection.setRequestMethod("GET");
			
			//连接
			connection.connect();
			// 得到响应码
			int responseCode = connection.getResponseCode();
			// 如果响应码是200,代表请求成功
			if (responseCode == 200) {
				// 得到输入流,包含请求到的数据
				InputStream inputStream = connection.getInputStream();
				// 记录每一行读到的数据
				String s = "";
				// 追加流里的数据
				StringBuffer buffer = new StringBuffer();
				// 读出流里的数据
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(inputStream));
				// 只要不等于null,流里就一直有数据,就要一直循环读取
				while ((s = bufferedReader.readLine()) != null) {
					buffer.append(s);
				}
				String data = buffer.toString();
				System.out.println(data);
				// 解析数据
				Gson gson = new Gson();

				Bean bean = gson.fromJson(data, Bean.class);
				// 子线程不能更新UI,通过handler发送到主线程
				Message msg = Message.obtain();
				msg.obj = bean;
				handler.sendMessage(msg);

			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值