天天看点

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