获取数据工具类代码展示如下:
···注:获取网络数据要在次线程里,耗时操作不能放在主线程里,否则会出现ANR(应用程序无响应),务必不要忘了加联网权限
public class Tools {
//获取网络文本的方法
public static String getText(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder s = new StringBuilder();
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
s.append(temp);
}
String string = s.toString();
return string;
}else {
Log.e("TAG","ss" );
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
//获取网络图片的方法
public static Bitmap getBitmap(String urlBitmap) {
try {
URL url = new URL(urlBitmap);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code==200){
//开始获取图片
InputStream inputStream = urlConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
-------------------------------------------------------------------------
以下是解析获取过来的文本数据
new Thread(){
@Override
public void run() {
super.run();
//获取文本数据
String text = Tools.getText(urlString);
//开始解析
Gson gson = new Gson();
Phone phone = gson.fromJson(text, Phone.class);
//获得解析完的集合
result = phone.getResult();
final Message msg = new Message();
msg.what=1;
msg.obj=result;
handler.sendMessage(msg);
}
}.start();