gson 数组 httpclient

来源:互联网 发布:qq飞车截图机器人源码 编辑:程序博客网 时间:2024/05/21 09:18
package com.example.a07_zhoukao_01;import android.os.AsyncTask;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.widget.ListView;import android.widget.TextView;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.ssl.AllowAllHostnameVerifier;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.lang.reflect.Type;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {    private ListView lv;    private List<String> list=new ArrayList<>();    private int index=0;    //每过3秒钟切换一条,下方展示一个列表    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 0) {                String json= (String) msg.obj;                Log.i("123",json);                Gson gson = new Gson();                Type type = new TypeToken<List<String>>() {}.getType();                List<String> jsonlist = gson.fromJson(json, type);                Log.i("---------",jsonlist.size()+"长度");                try {                    JSONArray jsonArray = new JSONArray(json);                    for (int i=0;i<jsonArray.length();i++){                        String string=jsonArray.getString(i);                        list.add(string);                    }                    text_toutiao.setText(list.get(index));                    handler.sendEmptyMessageDelayed(1,3000);                } catch (Exception e) {                    e.printStackTrace();                }            }else if (msg.what == 1) {                index++;                index=index%list.size();                text_toutiao.setText(list.get(index));                handler.sendEmptyMessageDelayed(1,3000);            }        }    };    private TextView text_toutiao;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text_toutiao = (TextView) findViewById(R.id.text_toutiao);        lv = (ListView) findViewById(R.id.lv);        getDataConnection();        getDataClient();    }    //2.   创建HttpUrlConnection请求的方法,传入参数为请求的url    private void getDataConnection() {        new Thread() {            @Override            public void run() {                String path = "http://www.toutiao.com/hot_words/";                try {                    URL url = new URL(path);                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(5000);                    connection.setReadTimeout(5000);                    int responseCode = connection.getResponseCode();                    if (responseCode == 200) {                        //4.   进入页面时主线程创建Handler对象并重写处理消息的方法                        InputStream inputStream = connection.getInputStream();                        String json = streamTostring(inputStream, "utf-8");                        Log.i("22222", json);                        Message message = Message.obtain();                        message.what = 0;                        message.obj = json;                        handler.sendMessage(message);                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        }.start();    }    //3.   创建HttpClient请求的方法,传入参数为请求的url    private void getDataClient() {        //5.   自定义一个AsyncTask的类并重写其中必要的两个方法        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {            @Override            protected String doInBackground(Void... voids) {                try {                    SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());                    HttpClient client = new DefaultHttpClient();                    String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1";                    HttpGet httpGet = new HttpGet(path);                    HttpResponse response = client.execute(httpGet);                    int statusCode = response.getStatusLine().getStatusCode();                    if (statusCode == 200) {                        InputStream inputStream = response.getEntity().getContent();                        String json = streamTostring(inputStream, "utf-8");                        Log.i("666660", json);                        return json;                    }                } catch (Exception e) {                    e.printStackTrace();                }                return null;            }            @Override            protected void onPostExecute(String json) {                Gson gson = new Gson();                ClientDataBean clientDataBean = gson.fromJson(json, ClientDataBean.class);                if (clientDataBean != null) {                    List<ClientDataBean.NewslistBean> list=clientDataBean.getNewslist();                    //6.   创建列表适配器,                    MyAdapter adapter = new MyAdapter(MainActivity.this,list);                    lv.setAdapter(adapter);                }            }        };        asyncTask.execute();    }    private String streamTostring(InputStream inputStream, String ss) {        try {            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, ss);            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            String s = null;            StringBuilder builder = new StringBuilder();            while ((s = bufferedReader.readLine()) != null) {                builder.append(s);            }            bufferedReader.close();            return builder.toString();        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}
原创粉丝点击