网络获取json解析json以及子线程显示
import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONObject; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.SAXParserFactory; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendRequest = (Button) findViewById(R.id.send_request); sendRequest.setOnClickListener(this); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); } @Override public void onClick(View v) { if (v.getId() == R.id.send_request) { // sendRequestWithHttpURLConnection(); sendRequestWithOkHttp(); /* String url = "http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"; HttpUtil.sendHttpRequest(url, new HttpCallbackListener() { @Override public void onFinish(String response) { showResponse(response); } @Override public void onError(Exception e) { } });*/ } } private void sendRequestWithHttpURLConnection() { // 开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); // 下面对获取到的输入流进行读取 reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } showResponse(response.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } }).start(); } private void sendRequestWithOkHttp() { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() // 指定访问的服务器地址是电脑本机 .url("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9") .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); String data = responseData.replace("try{jsonp9(", ""); data = data.substring(0, data.length() - 15); parseJSONWithGSON(data); // parseJSONWithJSONObject(data); // parseXMLWithSAX(responseData); // parseXMLWithPull(responseData); // showResponse(responseData); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void parseXMLWithPull(String xmlData) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser = factory.newPullParser(); xmlPullParser.setInput(new StringReader(xmlData)); int eventType = xmlPullParser.getEventType(); String id = ""; String name = ""; String version = ""; while (eventType != XmlPullParser.END_DOCUMENT) { String nodeName = xmlPullParser.getName(); switch (eventType) { // 开始解析某个结点 case XmlPullParser.START_TAG: { if ("id".equals(nodeName)) { id = xmlPullParser.nextText(); } else if ("name".equals(nodeName)) { name = xmlPullParser.nextText(); } else if ("version".equals(nodeName)) { version = xmlPullParser.nextText(); } break; } // 完成解析某个结点 case XmlPullParser.END_TAG: { if ("app".equals(nodeName)) { Log.d("MainActivity", "id is " + id); Log.d("MainActivity", "name is " + name); Log.d("MainActivity", "version is " + version); } break; } default: break; } eventType = xmlPullParser.next(); } } catch (Exception e) { e.printStackTrace(); } } private void parseXMLWithSAX(String xmlData) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); ContentHandler handler = new ContentHandler(); // 将ContentHandler的实例设置到XMLReader中 xmlReader.setContentHandler(handler); // 开始执行解析 xmlReader.parse(new InputSource(new StringReader(xmlData))); } catch (Exception e) { e.printStackTrace(); } } private void parseJSONWithJSONObject(String jsonData) { try { JSONArray jsonArray = new JSONArray(jsonData); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String id = jsonObject.getString("id"); String name = jsonObject.getString("name"); String version = jsonObject.getString("version"); Log.d("MainActivity", "id is " + id); Log.d("MainActivity", "name is " + name); Log.d("MainActivity", "version is " + version); } } catch (Exception e) { e.printStackTrace(); } } private void parseJSONWithGSON(String jsonData) { final TestEntity appList = fromToJson(jsonData, TestEntity.class); /* for (TestEntity app : appList) { Log.d("MainActivity", "id is " + app.getCode()); Log.d("MainActivity", "name is " + app.getTimestamp()); Log.d("MainActivity", "version is " + app.getData().getAllNum()); }*/ final Handler handler = new Handler(Looper.getMainLooper()); new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { List<TestEntity.DataBean.VlistBean> list = appList.getData().getVlist(); FruitAdapter adapter = new FruitAdapter(list,MainActivity.this); recyclerView.setAdapter(adapter); } }); } }).start(); } private void showResponse(final String response) { runOnUiThread(new Runnable() { @Override public void run() { // 在这里进行UI操作,将结果显示到界面上 // responseText.setText(response); } }); } //根据泛型返回解析制定的类型 public <T> T fromToJson(String json, Type listType) { Gson gson = new Gson(); T t = null; t = gson.fromJson(json, listType); return t; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 17
- 粉丝: 1503
- 资源: 5
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- toad.selection.stepwise函数示例的数据集和代码
- Maxwell 与 Workbench联合仿真,电机时空二维电磁力谐波优化设计 这里仅做一个demo,为了节约仿真时间,我直接用的响应面模块进行仿真和优化,可以成Optislang进行多参数多目标优
- Redis-7.4.1
- 开源深度学习模型部署工具箱MMDeploy
- Unity毛笔字+笔锋效果
- COMSOL变压器仿真 变压器三维仿真模型 声-固耦合 振动声场comsol仿真模型 运行有效
- 基于动态非合作博弈的大规模电动汽车实时优化调度复现,用鲸鱼算法编写
- 用digital数字电路软件实现一位复用器
- Django admin登录页面美化
- 用友T3余额表内存溢出错误解决方法和ufformat.mdb文件
- 直流电机调速pid,极点配置,LQR跟踪控制 matlab simulink仿真,含12页报告 程序可扩展到其他被控对象上去 199 整套,含程序和报告
- comsol二维光子晶体角态 单胞能带,超胞能带,边界态以及角态计算
- 一个使用 Java 的 JavaFX 库来实现的满屏烟花效果的代码例子
- 光伏发电+boost+储能+双向dcdc+并网逆变器控制参考资料 光伏发电+boost+储能+双向dcdc+并网逆变器控制(低压用户型电能路由器仿真模型)【含笔记+建模参考】 包含Boost、Buck
- 基于java+springboot+vue+mysql的北部湾地区助农平台 源码+数据库+论文(高分毕业设计).zip
- 批处理命令追加bin文件的 CRC