`private void getData() {
// 要访问的服务器地址
String path = “http://172.20.81.59:8080/bwie/json/index.json“;
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();
}
}`