AndroidStudio——利用APIStore获取网络新闻

HttpJsonActivity

public class HttpJsonActivity extends AppCompatActivity {
    private Spinner channel;
    private TextView tv;
    private SimpleAdapter sa;
    private List<Map<String, String>> channelList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_json);
        tv = (TextView) findViewById(R.id.tv);
        channel = (Spinner) findViewById(R.id.channel);
        channelList = new ArrayList<>();
        sa = new SimpleAdapter(this, channelList, android.R.layout.simple_spinner_item
                , new String[]{"name"}, new int[]{android.R.id.text1});
        channel.setAdapter(sa);
        new GetChannel().execute();

        channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> map = channelList.get(position);
                String channelName = map.get("name");
                String channelId = map.get(channelName);
                String url = UrlUtil.newsUrl + "?channelId=" + channelId
                        + "&channelName=" + channelName
                        + "needContent=1"
                        + "&needHtml=1";
                new GetNews().execute(url);
            }

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

            }
        });
    }

    //获取频道
    public class GetChannel extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.HttpGet(UrlUtil.channelUrl);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("")) {
                Toast.makeText(getBaseContext(), "网络连接异常", Toast.LENGTH_SHORT).show();
            }
            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) {

            return HttpUtil.HttpGet(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("")) {
                tv.setText("没有数据");
            } else {
                tv.setText(s);
            }
        }
    }

//    public class GetJson extends AsyncTask<String, Void, String> {
//
//        @Override
//        protected String doInBackground(String... strings) {
//            HttpURLConnection con = null;
//            InputStream is = null;
//            BufferedReader reader = null;
//            StringBuilder sbd = new StringBuilder();
//            try {
//                URL url = new URL("http://apis.baidu.com/showapi_open_bus/channel_news/channel_news\n");
//                con = (HttpURLConnection) url.openConnection();
//                con.setConnectTimeout(5 * 1000);
//                con.setReadTimeout(5 * 1000);
//                con.setRequestMethod("GET");
//                con.setRequestProperty("apikey", "5b46143955a4b1ff1b470a94315625cd\n");
//                // con.connect();
//                if (con.getResponseCode() == 200) {
//                    is = con.getInputStream();
//                    reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//                    String strRead = null;
//                    while ((strRead = reader.readLine()) != null) {
//                        sbd.append(strRead);
//                        sbd.append("\n");
//                    }
//                }
//            } catch (MalformedURLException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                if (is != null) {
//                    try {
//                        reader.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//            return sbd.toString();
//        }
//
//        @Override
//        protected void onPostExecute(String fileName,String s) {
//            super.onPostExecute(s);
//            FileUitlity.saveFileToSdcard("sd.txt",s);
//        }
//    }

}

activity_http_json布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.example.dell.jreduch008.HttpJsonActivity">

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/channel"></Spinner>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/channel"
        android:id="@+id/sv">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tv"/>
    </ScrollView>
</RelativeLayout>

工具类:
1.FileUitlity

public class FileUitlity {
    private static String ROOT_CACHE;
    private static FileUitlity instance = null;
    private FileUitlity() {
    }
    public static FileUitlity getInstance(Context context,String root_dir) {
        if (instance == null) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"
                        + root_dir + "/");
            } else {
                ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/"+root_dir+"/");
            }
            File dir = new File(ROOT_CACHE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            instance = new FileUitlity();
        }
        return instance;
    }
    public File makeDir(String dir) {
        File fileDir = new File(ROOT_CACHE + dir);
        if (fileDir.exists()) {
            return fileDir;
        } else {
            fileDir.mkdirs();
            return fileDir;
        }
    }
    public static String saveFileToSdcard(String fileName,String content){
        String state = Environment.getExternalStorageState();
        if(!state.equals(Environment.MEDIA_MOUNTED)){
            return "SD卡未就绪";
        }
        File root = Environment.getExternalStorageDirectory();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(root+"/"+fileName);
            fos.write(content.getBytes());
            return "ok";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}

2.HttpUtil

public class HttpUtil {
    public static String HttpGet(String uri){
        HttpURLConnection con = null;
        BufferedReader reader = null;
        InputStream is = null;
        StringBuilder sbd = new StringBuilder();
        try {
            URL url = new URL(uri);
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5*1000);
            con.setReadTimeout(5*1000);
            con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");
            con.connect();
            if(con.getResponseCode()==200){
                is = con.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sbd.append(strRead);
                    sbd.append("\r\n");
                }
                return sbd.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}

3. UrlUtil

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";

}

运行结果:

这里写图片描述

这里写图片描述

这里写图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值