Android中調用api接口


一、Android中調用api接口步驟                                      

1.創建一個類繼承AsyncTask類使該類作為一個異步任務類

2.該類中重寫doInBackground方法和onPostExecute方法

3.在需要調用api接口的Activty中new一個該類並調用api地址即可

 

 

二、示例代碼                                                                    

1.異步任務類中的代碼

 注意:其中重寫的第一個方法(doInBackground)是負責調用api接口並接收返回數據的(return的數據自動傳入第二個方法),

    而第二個方法(onPostExecute)是負責對傳入的json數據進行操作的

 
         
//泛型用從左到右分別表示 
//1.傳入url參數類型,2.一般為Void對象(有進度條的需求才使用),3.doInBackGround方法返回值類型

public
class GetItemProductTask extends AsyncTask<String,Void,String> { //需要傳入內容的控件
private TextView title; private TextView price; private TextView desc; //構造器 public GetItemProductTask(TextView title, TextView price, TextView desc) {
    
this.title = title; this.price = price; this.desc = desc; } //負責調用api接口接收數據的方法
   //該方法里代碼直接復制即可,該方法獲得的json數據會自動傳入onPostExecute方法
@Override protected String doInBackground(String... strings) { try { HttpURLConnection con = (HttpURLConnection) new URL(strings[0]).openConnection(); int code = con.getResponseCode(); if(code==200){ InputStream is = con.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = 0; byte[] buf = new byte[1024]; while((n=is.read(buf))!=-1) { out.write(buf, 0, n); } String str = out.toString("UTF-8"); return str; } } catch (IOException e) { e.printStackTrace(); } return null; } //負責操作數據的方法 //doInBackground方法獲得的數據會自動傳到該方法 @Override protected void onPostExecute(String json) { //使用Gson解析json數據轉Map對象 Map<String,String> map = new Gson().fromJson(json, Map.class); if (map!=null){ title.setText(map.get("title")); price.setText(map.get("price")); desc.setText(map.get("sell_point")); } } }

 

2.Activity中的代碼

//傳入控件以及地址即可執行異步任務
new GetItemProductTask(title,price,desc)
                    .execute("你的api地址");

 

 

 三、(拓展)異步請求圖片地址並適配到圖片組件中      

//圖片的返回類型必須為Bitmap
public class ImgUrlToViewTask  extends AsyncTask<String,Void,Bitmap> {
    private ImageView imageView;

    public ImgUrlToViewTask(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... strings) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(strings[0]).openConnection();
            conn.connect();
            int code = conn.getResponseCode();
            if(code == 200){
                InputStream is = conn.getInputStream();
                Bitmap bmp = BitmapFactory.decodeStream(is);
                /*if(bmp!=null){
                    MainActivity.cache.put(strings[1],bmp);
                }*/
                return bmp;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //適配圖片到控件中
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if(bitmap!=null) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM