标签:
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; @Override protected 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() { @Override public 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(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } //获取频道 public class GetChanel extends AsyncTask<Void,Void,String>{ @Override protected String doInBackground(Void... strings) { 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); channe1List.add(map); } sa.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } } //获取新闻 public class GetNew extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... strings) { return HttpUtil.HttpGet(strings[0]); } @Override protected 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"> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/channe1" ></Spinner> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/channe1" > <TextView android: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; @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<String,Void,String> { // 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(); // } // } // } // } } </strong></span>
Android——百度APIstore+Json——获取新闻频道+新闻数据
标签:
原文地址:http://blog.csdn.net/zhangyufeng0126/article/details/52233899