public class MyHttpuriconntion extends Thread { private Handler handler; private String url; public MyHttpuriconntion(Handler handler, String url) { this.handler = handler; this.url = url; } public void getjson(){ new Thread(){ @Override public void run() { String data = getData(); Gson gson = new Gson(); Userbean json = gson.fromJson(data, Userbean.class); if(json!=null){ Message message = Message.obtain(); message.what=0; message.obj =json; handler.sendMessage(message); } } }.start(); } public String getData(){ try { URL myurl = new URL(url); HttpURLConnection connection = (HttpURLConnection) myurl.openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if(connection.getResponseCode()==200){ InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GBK")); StringBuilder builder = new StringBuilder(); String str; if((str =reader.readLine())!=null){ builder.append(str); } return builder.toString(); } } catch (Exception e) { e.printStackTrace(); } return null; }}
在需要用到类中调用,实例化此工具类,通过类中的方法得到json串
public class FragmentJY extends Fragment{ private ListView mLv; private Handler handler = new Handler(){ private List<Userbean.DataBean> mDatalist; @Override public void handleMessage(Message msg) { if(msg.what==0){//得到message绑定的消息 Userbean bean= (Userbean) msg.obj;
//得到集合 List<Userbean.DataBean> mDatalist = bean.getData();//设置适配器MyAdapter adapter = new MyAdapter(mDatalist, getActivity()); mLv.setAdapter(adapter); //缓存数据的方法 MyHelper myHelper = new MyHelper(getActivity()); SQLiteDatabase db = myHelper.getReadableDatabase(); for(Userbean.DataBean u:mDatalist){ ContentValues value=new ContentValues(); value.put("url",u.getPic_url()); value.put("detectionItem",u.getNews_summary()); value.put("categoryTitle",u.getNews_title()); db.insert("mytable",null,value); } } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, null); mLv = (ListView) view.findViewById(R.id.list_view);//实例化工具类 MyHttpuriconntion myHttpuriconntion = new MyHttpuriconntion(handler, MyUrl.url); //得到解析方法myHttpuriconntion.getjson(); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }
HttpURLConnection 单独封装网络请求工具类
最新推荐文章于 2020-08-14 09:30:00 发布