AsyncTask<Void,Void,String> asyncTask=new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); String path2=“”; HttpClient client=new DefaultHttpClient(); HttpGet httpGet=new HttpGet(path2); try { HttpResponse execute = client.execute(httpGet); int statusCode = execute.getStatusLine().getStatusCode(); if (statusCode==200){ InputStream inputStream = execute.getEntity().getContent(); String json = streamtoString(inputStream, "utf-8"); return json; } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { Gson gson=new Gson(); DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class); newslist = dataDataBean.getNewslist(); MyAdapter adapter=new MyAdapter(newslist,MainActivity.this); lv.setAdapter(adapter); } }; asyncTask.execute(); }
private String streamtoString(InputStream inputStream, String s) { try { InputStreamReader isr=new InputStreamReader(inputStream); BufferedReader br=new BufferedReader(isr); String len; StringBuilder sb=new StringBuilder(); while((len=br.readLine())!=null){ sb.append(len); } br.close(); return sb.toString(); } catch (IOException e) { } return null; }
本文介绍了一个使用AsyncTask从网络获取JSON数据的例子。通过设置SSL连接的信任验证,使用HttpClient发起GET请求,并解析返回的JSON数据到自定义的数据模型中,最后更新UI显示获取的数据。
156

被折叠的 条评论
为什么被折叠?



