HttpUrlConnection+Handler 和 HttpClient+AsyncTask 实现页面的基本操作

package com.example.myzhoukao_one.Activity;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myzhoukao_one.R;
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 org.json.JSONException;

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 TextView textView;
    private ListView listView;

    private int index = 0;

    private List<String> list = new ArrayList<>();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
               String json = (String) msg.obj;
                Log.i("---",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);
                    }

                    textView.setText(list.get(index));

                    handler.sendEmptyMessageDelayed(1,3000);
              } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else if( msg.what == 1){
                index ++;

                index = index%list.size();

                textView.setText(list.get(index));

                handler.sendEmptyMessageDelayed(1,3000);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text_tou);
        listView = (ListView) findViewById(R.id.list_view);

        getTouTiao();

        getListViewData();
    }

    private void getListViewData() {
        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();

                    HttpGet httpGet = new HttpGet("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1");

                    HttpResponse httpResponse = client.execute(httpGet);

                    int statusCode = httpResponse.getStatusLine().getStatusCode();

                    if (statusCode == 200){
                        InputStream inputStream = httpResponse.getEntity().getContent();

                        String json = streamToString(inputStream,"utf-8");

                        return json;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                Gson gson = new Gson();


                DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);

                List<DataDataBean.NewslistBean> newslist = dataDataBean.getNewslist();

                //设置适配器
                MyAdapter myAdapter = new MyAdapter(newslist, MainActivity.this);

                listView.setAdapter(myAdapter);

            }

        };

        asyncTask.execute();
    }


    private void getTouTiao(){
         new Thread(){
             @Override
             public void run(){

                 try {
                     URL url = new URL("http://www.toutiao.com/hot_words/");

                     HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                     connection.setRequestMethod("GET");
                     connection.setReadTimeout(5000);
                     connection.setConnectTimeout(5000);

                     int responseCode = connection.getResponseCode();
                     if(responseCode == 200){
                         InputStream inputStream = connection.getInputStream();

                         String json = streamToString(inputStream,"utf-8");

                         Message message = Message.obtain();
                         message.what = 0;
                         message.obj = json;
                         handler.sendMessage(message);
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }.start();
    }

    private String streamToString(InputStream inputstream,String charset){
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputstream,charset);

            BufferedReader bufferedreader = new BufferedReader(inputStreamReader);

            String s;

            StringBuilder builder = new StringBuilder();
            while((s=bufferedreader.readLine())!=null){
                   builder.append(s);
            }
            bufferedreader.close();

            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值