Android---如何利用API实时获取各频道新闻?

版权声明:一篇成长日记文章,没什么转载价值。 https://blog.csdn.net/zhaoyanga14/article/details/52234555

基本上万事俱备了,博主我把开发新闻阅读器的相关知识都整理好了,接下来几天我要搞一个新闻阅读器(*^__^*) ~


本次实例包含了利用API(从“百度APIStore”上找的),从网络上实时获取各种频道的新闻。


接下来,我们首先建一个Layout,上面放一个Spinner,用来展现各种新闻频道,而下面,我们放一个TextView,当选中Spinner中相应的频道时,TextView中则会加载从网络获取的该频道实时新闻。

这里先给大家贴个工具类,用来从网络获取信息:

public class UrlUtil {
    //获取频道的网络接口
    public static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
    //获取频道对应新闻的网络接口
    /*
    get 请求参数
    *channelId 新闻频道id,必须精确匹配
     channelName 新闻频道名称,可模糊匹配
     title 新闻标题,模糊匹配
     page 页数,默认1。每页最多20条记录
    *needContent 是否需要返回正文,1为需要,其他为不需要
    *needHtml 是否需要返回正文的html格式,1为需要,其他为不需要
     */
    public static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";

}

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    tools:context="jerehdu.com.jerehdu04.HttpNewsActivity"
    android:orientation="vertical">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingRight="12dp">
            <Spinner
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:id="@+id/channel"
                android:gravity="center">
            </Spinner>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/news"/>
        </LinearLayout>

    </ScrollView>


</LinearLayout>


Activity:

public class HttpNewsActivity extends AppCompatActivity {

    private Spinner channel;
    private TextView show;
    private SimpleAdapter sa;
    private List<Map<String,String>> channelList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_news);
        channel = (Spinner) findViewById(R.id.channel);
        show = (TextView) findViewById(R.id.news);
        channelList = new ArrayList<>();
        sa = new SimpleAdapter(this,channelList,
                android.R.layout.simple_list_item_1,
                new String[]{"name"},new int[]{android.R.id.text1});
        channel.setAdapter(sa);
        String httpUrl = UrlUtil.channelUrl;
        new GetNewsChannel().execute(httpUrl);

        //Spinner监听
        channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map map = channelList.get(position);
                String channelName = (String) map.get("name");
                String channelId = (String) map.get(channelName);
                String[] strings = new String[]{channelId,channelName};
                new GetNews().execute(strings);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //获取新闻频道
    public class GetNewsChannel extends AsyncTask<String,Void,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            return HttpUtil.HttpGet(strings[0]);
        }

        //在UI线程(主线程)中执行命令
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("")){
                Toast.makeText(getBaseContext(),"没有数据",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject obj = new JSONObject(s);
                JSONObject body = obj.getJSONObject("showapi_res_body");
                JSONArray ja = body.getJSONArray("channelList");
                for(int i = 0;i<ja.length();i++){
                    JSONObject channelObj = (JSONObject) ja.get(i);
                    String id = channelObj.getString("channelId");
                    String name = channelObj.getString("name");
                    Map map = new HashMap();
                    map.put("name",name);
                    map.put(name,id);
                    channelList.add(map);
                }
                sa.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    //获取新闻内容
    public class GetNews extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            String httpUrl = UrlUtil.newsUrl;
            String httpArg = "channelId="+params[0]+"&" +
                    "channelName="+params[1]+"&" +
                    "title=&" +
                    "page=1&" +
                    "needContent=1&" +
                    "needHtml=1";
            String jsonResult = httpUrl + "?" + httpArg;
            return HttpUtil.HttpGet(jsonResult);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("")){
                show.setText("没有数据或无网络连接");
            }else {
                jsonHandle(s);
            }
        }

    }

    //解析Json
    public void jsonHandle(String s){
        InputStream is ;
        BufferedReader reader = null;
        StringBuilder sbd = new StringBuilder();
        try {
            JSONObject obj = new JSONObject(s);
            JSONObject body = obj.getJSONObject("showapi_res_body");
            JSONObject body2 = body.getJSONObject("pagebean");
            JSONArray ja = body2.getJSONArray("contentlist");
            for(int i = 0;i<ja.length();i++){
                JSONObject newsObj = (JSONObject) ja.get(i);
                String news1 = newsObj.getString("content");
                sbd.append(news1);
                sbd.append("\t\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        show.setText(sbd.toString());
    }

}

预览图:

扫描二维码关注公众号,回复: 5352517 查看本文章



猜你喜欢

转载自blog.csdn.net/zhaoyanga14/article/details/52234555