Android——百度APIstore+Json——获取新闻频道+新闻数据
16lz
2021-01-23
Android——百度APIstore+Json——获取新闻频道+新闻数据
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 "";}}
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
<?xml version="1.0" encoding="utf-8"?>
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; @Override protected 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 { // onPostExecute在主线程中执行命令 //doInBackground在子线程中执行命令 //doInBackground执行之后会到onPostExecute中 @Override protected 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;// } @Override protected 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();// }// }// }// }}
更多相关文章
- android ListView内数据的动态添加与删除
- Android使用自带JSONObject解析JSON数据
- Android之数据存储-手机存储中
- 手动修改Android数据库数据
- Android批量插入数据
- Android:如何关/启 自动同步(Auto Sync )和背景数据(Background data
- Android 利用handler传递数据
- Android 官方数据库Room --- 配置
- 【Android】数据库 sqLite