Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android——百度APIstore+Json——獲取新聞頻道+新聞數據

Android——百度APIstore+Json——獲取新聞頻道+新聞數據

編輯:關於Android編程

\

 

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> 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 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{

        @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{

    @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);}
    }
}

}





    
        
    


\

 

\

 

 

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();
//                }
//            }
//        }
//    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved