网络获取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
- 粉丝: 1498
- 资源: 5
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助