Android——百度APIstore+Json——获取新闻频道+新闻数据
Android——百度APIstore+Json——获取新闻频道+新闻数据
<span style="font-size:18px;"><strong>package com.example.jreduch08.util;import android.content.Context;
import android.os.Environment;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;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 "";}
}
</strong></span>
package com.example.jreduch08.util;import android.util.Log;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;/*** Created by 冲天之峰 on 2016/8/17.*/
public class HttpUtil {public static String HttpGet(String uri){HttpURLConnection con = null;//为了抛异常InputStream is = null;BufferedReader reader=null;String result=null;StringBuffer sbf=new StringBuffer();try {URL url = new URL(uri);con = (HttpURLConnection) url.openConnection();con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");con.setConnectTimeout(5 * 1000);con.setReadTimeout(5 * 1000);//http响应码200成功 404未找到 500发生错误if (con.getResponseCode() == 200) {is = con.getInputStream();reader =new BufferedReader(new InputStreamReader(is,"UTF-8"));String strRead=null;while ((strRead = reader.readLine())!=null) {sbf.append(strRead);sbf.append("\r\n");Log.d("==j==", "200");}reader.close();result=sbf.toString();Log.d("=====",result);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (con != null) {con.disconnect();}}return result;}}
package com.example.jreduch08.util;/*** Created by 冲天之峰 on 2016/8/17.*/
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";
}
以上是三个工具+方法
package com.example.jreduch08;import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;import com.example.jreduch08.util.HttpUtil;
import com.example.jreduch08.util.UrlUtil;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class HttpJsonActivity extends AppCompatActivity {private String httpurl;private TextView tv;private Spinner channe1;private SimpleAdapter sa;private List<Map<String,String>> channe1List;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_http_json);tv=(TextView)findViewById(R.id.tv);channe1=(Spinner)findViewById(R.id.channe1);channe1List=new ArrayList<>();sa=new SimpleAdapter(this,channe1List,android.R.layout.simple_spinner_item,new String[]{"name"},new int[]{android.R.id.text1});channe1.setAdapter(sa);new GetChanel().execute();channe1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {Map<String,String> map=channe1List.get(position);String channelName=map.get ("name");String channelId=map.get(channelName);String url=UrlUtil.newsUrl+"?channelId="+channelId+"&channerlName="+channelName+"&needContent=1"+"&needHtml=1";new GetNew().execute(url);// tv.setText(channe1.getSelectedItem().toString());
// Toast.makeText(getBaseContext(),"点击了新闻"+position,Toast.LENGTH_SHORT).show();// Toast.makeText(getBaseContext(),channe1.getSelectedItemId()+"",Toast.LENGTH_SHORT).show();}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}});}
//获取频道public class GetChanel extends AsyncTask<Void,Void,String>{@Overrideprotected String doInBackground(Void... strings) {return HttpUtil.HttpGet(UrlUtil.channelUrl);}@Overrideprotected 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);channe1List.add(map);}sa.notifyDataSetChanged();} catch (JSONException e) {e.printStackTrace();}}}
//获取新闻public class GetNew extends AsyncTask<String,Void,String>{@Overrideprotected String doInBackground(String... strings) {return HttpUtil.HttpGet(strings[0]);}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);if (s.equals("")){tv.setText("没有数据");}else{tv.setText(s);}}
}}
<?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.jreduch08.HttpJsonActivity">
<Spinnerandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/channe1"></Spinner><ScrollViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/channe1"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/tv"/></ScrollView>
</RelativeLayout>
<span style="font-size:18px;"><strong>package com.example.jreduch08;import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;import com.example.jreduch08.util.FileUitlity;
import com.example.jreduch08.util.HttpUtil;
import com.example.jreduch08.util.UrlUtil;public class APIActivity extends AppCompatActivity {private String httpurl;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_api);tv= (TextView) findViewById(R.id.tv);httpurl="http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";new MyGetJson().execute(UrlUtil.channelUrl);}//访问网络异步任务类public class MyGetJson extends AsyncTask<String,Void,String> {// onPostExecute在主线程中执行命令//doInBackground在子线程中执行命令//doInBackground执行之后会到onPostExecute中@Overrideprotected String doInBackground(String... params) {return HttpUtil.HttpGet(params[0]);}// HttpURLConnection con = null;//为了抛异常
// InputStream is = null;
// BufferedReader reader=null;
// String result=null;
// StringBuffer sbf=new StringBuffer();
//
// try {
// URL url = new URL(httpurl);
// con = (HttpURLConnection) url.openConnection();
// con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");
// con.setConnectTimeout(5 * 1000);
// con.setReadTimeout(5 * 1000);
// //http响应码200成功 404未找到 500发生错误
// if (con.getResponseCode() == 200) {
// is = con.getInputStream();
// reader =new BufferedReader(new InputStreamReader(is,"UTF-8"));
// String strRead=null;
// while ((strRead = reader.readLine())!=null) {
// sbf.append(strRead);
// sbf.append("\r\n");
// Log.d("==j==", "200");
// }
// reader.close();
// result=sbf.toString();
// Log.d("=====",result);
// }
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (is != null) {
// try {
// is.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }if (con != null) {
// con.disconnect();
// }
// }
// return result;
// }@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);tv.setText(s);saveFile(s);Log.d("==j==", "2");}}//保存文件到SD卡public void saveFile(String s) {Toast.makeText(this, FileUitlity.saveFileToSdcard("/abcdef.txt",s),Toast.LENGTH_SHORT).show();}
// FileOutputStream fos=null;
// //获取SD卡状态
// String state= Environment.getExternalStorageState();
// //判断SD卡是否就绪
// if(!state.equals(Environment.MEDIA_MOUNTED)){
// Toast.makeText(this,"请检查SD卡",Toast.LENGTH_SHORT).show();
// return;
// }
// //取得SD卡根目录
// File file= Environment.getExternalStorageDirectory();
//
// try {
// Log.d("=====SD卡根目录:",file.getCanonicalPath().toString());File myFile=new File(file.getCanonicalPath()+"/sd.txt");fos=new FileOutputStream(myFile);
// //输出流的构造参数1可以是 File对象 也可以是文件路径
// //输出流的构造参数2:默认为False=>覆盖内容;ture=》追加内容
// //追加 ,ture
// fos=new FileOutputStream(file.getCanonicalPath()+"/sdsdsd.txt");
// String str=s;
// fos.write(str.getBytes());
// Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
// } catch (IOException e) {
// e.printStackTrace();
// }finally {
// if (fos!=null){
// try {
// fos.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
}
</strong></span>
Android——百度APIstore+Json——获取新闻频道+新闻数据相关推荐
- android 百度地图api密钥,Android百度地图开发获取秘钥之SHA1
最近在做一个关于百度地图的开发. 不过在正式开发之前还必须要在百度地图API官网里先申请秘钥,而在申请秘钥的过程中,就需要获取一个所谓的SHA1值. 如上所示,但是由于不是正式开发,所以以上的发布版和 ...
- Android百度地图屏蔽油站,怎么用android百度地图api获取离当前位置最近的加油站...
匿名用户 1级 2016-09-15 回答 import com.baidu.location.BDLocation; import com.baidu.location.BDLocationList ...
- android调用百度地图第一次定位失败,android 百度地图 定位获取位置失败 62错误...
mysql 常用语句模板 插入INSERT IGNORE INTO test (`f1`, `f2`, `f3`) VALUES (v1,v2,v3); 更新update test set f1=v1 ...
- android 新闻频道,GitHub - xiyy/TopNews: 一款Android新闻客户端,并提供电视台直播功能...
TopNews 一款Android新闻客户端,独立开发完成,主要功能包括: 1 新闻频道分类,头条.社会.国内.娱乐.体育.军事.科技.财经.时尚 使用ViewPager+FragmentPagerA ...
- android 新闻列表json,Android中通过ListView的实现简单新闻列表
请注明出处:http://blog.csdn.net/qq_23179075/article/details/78648703 Android中实现简单的新闻列表 "本文主要针对Androi ...
- httpclient调用京东万象数字营销频道新闻api实例
本人在使用httpclient做练习的时候,偶然发现京东万象上有一个免费的频道新闻调用api,故尝试之,因为官网文档只给出的java代码都是封装后的,所以我自己写了一遍,又写了一些注释.分享代码,供大 ...
- (android高仿系列)今日头条 --新闻阅读器 (三) 完结 、总结 篇
从写第一篇今日头条高仿系列开始,到现在已经过去了1个多月了,其实大体都做好了,就是迟迟没有放出来,因为我觉得,做这个东西也是有个过程的,我想把这个模仿中一步一步学习的过程,按照自己的思路写下来,在根据 ...
- Android开发——项目实例(五)集新闻、音乐、电影于一体的软件(带打包源码)
主页面 1.写界面 很明显,这个主界面采用了ViewPager和TabLayout实现界面滑动切换,在使用TabLayout之前记得导包,TabLayout需要导入的包. <?xml versi ...
- 仿腾讯新闻频道定制界面效果
转载请注明出处 http://blog.csdn.net/oddshou/article/details/73467589 更新: 仿腾讯新闻频道定制界面效果2 这个效果一直想做,最近项目无事决定着手 ...
最新文章
- python脚本设置linux环境变量_Linux环境变量export方法与修改文件方法的区别
- [sh]shell案例
- xib和storyboard小谈,
- fir.im Weekly - 给 Mac 应用开发者的教程
- JAVA企业级应用TOMCAT实战视频课程
- 学习 | egg.js 中间件和插件
- Web 浏览器相关的一些概念
- 使用C#生成word文件
- 【TSP】基于matlab遗传和模拟退火算法求解中国省会城市旅行商问题【含Matlab源码 1254期】
- c语言输入m行m列的二维数组,编写一个函数,用于计算具有n行和m列的二维数组中指定列的平均值以及数组各行的和的最小值。...
- 2003年高考语文全国最高分_2003年参加高考的同学们?你们考了多少分啊?再议2003年高考数学...
- 团队管理(一)-会议纪要的高效记录和执行
- 星巴克急了,瑞幸就稳了?
- java 导出txt_【Java】导入导出TXT文件
- excel项目计划_使用Excel计划您的聚会座位
- 测试进阶必备,这5款http接口自动化测试工具简直不要太香~
- 阿里巴巴淘系技术部拍卖部-春招提前批
- Arduino基础入门篇30—数字温度传感器DS18B20
- 提升用户体验 联想企业网盘从速度、数据管理、业务协同三方面入手
- (五)IEEE802.1Q与ISL
热门文章
- SpringBoot整合Thymleaf实现页面静态化
- nafxcw.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined问题解决
- Java方法创建及调用--------06
- moviepy图片合成视频
- cartographer 老版本 UKF
- iOS高仿微信完整源码,网易爱玩APP源码等
- 【GDOI2019Day1模拟2019.4.28】爱乐之城
- 用zookeeper体验监听服务器是否还活着
- 老闪创业那些事儿(58)——C轮融资变身超级独角兽
- 解决Ubuntu18.04版本高分辨率下导致字体过小问题