android--Baidu apistore+json--Get news Channel + news data

Source: Internet
Author: User
Tags response code save file

android--Baidu apistore+json--Get news Channel + news data



<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  ;p rivate 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 {F Iledir.mkdirs (); return filedir;}} Public StAtic string Savefiletosdcard (string filename,string content) {string state = Environment.getexternalstoragestate (); if ( !state.equals (environment.media_mounted)) {return ' SD card not ready ';} 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 the peak of cupola on 2016/8/17.        */public class Httputil {public static string HttpGet (String uri) {httpurlconnection con = null;//in order to throw an exception        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 response code 200 succeeded 404 Not found 500 An error occurred if (con.getresponsecode () = =) {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 the peak of cupola on 2016/8/17. */public class Urlutil {    //Get channel's network interface public    static String Channelurl = "Http://apis.baidu.com/showapi_open_bus /channel_news/channel_news ";    /* Get the channel corresponding news network interface      GET request parameters:       channelid    : News Channel ID, must be exact match       ChannelName  : News channel name, can blur match       title        : News title, Fuzzy matching       page         : page number, default 1. Up to 20 records per page       needcontent  : Whether you need to return the body, 1 is required       needhtml     : Whether you need to return the body HTML format, 1 is required     *    /Public static String Newsurl = "Http://apis.baidu.com/showapi_open_bus/channel_news/search_news";}

Above are three tools + methods

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 O Nitemselected (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 (), "clicked News" +position,toast.length_short). Show ()               ;            Toast.maketext (Getbasecontext (), Channe1.getselecteditemid () + "", Toast.length_short). Show ();    } @Override public void onnothingselected (adapterview<?> parent) {}}); }//get Channel public class Getchanel extends asynctask<void,void,string>{@Override protected String DoI        Nbackground (Void ... strings) {return httputil.httpget (Urlutil.channelurl);     } @Override protected void OnPostExecute (String s) {Super.onpostexecute (s);     if (S.equals (")") {Toast.maketext (Getbasecontext (), "No Data", 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 (); }}}//get news public class Getnew extends asynctask<string,void,string>{@Override protected Strin    G Doinbackground (String ... strings) {return Httputil.httpget (strings[0]);        } @Override protected void OnPostExecute (String s) {Super.onpostexecute (s);        if (S.equals ("")) {Tv.settext ("no data");    }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);        }//Access network Asynchronous task class public class Mygetjson extends asynctask<string,void,string> {//OnPostExecute execute command in main thread    Doinbackground executing commands in a child thread    Doinbackground executes to OnPostExecute @Override protected string Doinbackground (String ... params) {        Return Httputil.httpget (Params[0]); }//httpurlconnection con = null;//in order to throw exceptions//InputStream is = null;//BufferedReader reader                =null;//String result=null;//stringbuffer sbf=new stringbuffer ();////try {// URL url = new URL (httpurl);//con = (httpurlconnection) url.openconnection ();//con.se                Trequestproperty ("Apikey", "5B46143955A4B1FF1B470A94315625CD");//Con.setconnecttimeout (5 * 1000);// Con.setreadtimeout (5 * +);////http Response code 200 success 404 Not Found 500 error occurred//if (con.getresponsec Ode () = = +) {//is = Con.getinputstream ();//Reader =new BufferedReader (new InputS Treamreader (IS, "UTF-8"));//String strread=null;//while ((Strread = Reader.readline ())!=null) {//Sbf.append (Strread);//Sbf.append ("\                    r\n ");//LOG.D (" ==j== "," a ");//}//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) {sup    Er.onpostexecute (s);        Tv.settext (s);            SaveFile (s);        LOG.D ("==j==", "2"); }}//save file to sd card public void SaveFile (String s) {Toast.maketext (This, Fileuitlity.savefiletosdcard ("/abcde    F.txt ", s), Toast.length_short). Show ();        }//FileOutputStream fos=null;////Get SD card status//String state= environment.getexternalstoragestate ();// Determine if the SD card is ready//if (!state.equals (environment.media_mounted)) {//Toast.maketext (this, "Please check SD card", TOAST.L Ength_short). Show ();//return;//}////Get SD Card root directory//File file= Environment.getexternalstorag EDirectory ();////try {//LOG.D ("=====SD card root:", File.getcanonicalpath (). toString ());////file Myfile=new File (File.getcanonicalpath () + "/sd.txt")////fos=new FileOutputStream (myFile);////////output stream construction The parameter 1 can be a file object or a path to the files////////////output stream construction parameter 2: Default is false=> overlay content; ture= append///Append, ture//Fos=ne W FileOutputStream (File.getcanonicalpath () + "/sdsdsd.txt");//String str=s;//Fos.write (Str.getbytes ());//T Oast.maketext (This, "Save succeeded", Toast.length_short). Show ();/} catch (IOException e) {//E.printstacktrace ();                }finally {//if (fos!=null) {//try {//Fos.close ();// } catch (IOException e) {//E.printstacktrace ();//}//}//}//}} </strong></span>



android--Baidu apistore+json--Get news Channel + news data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.