Android async-http 的简单用法(菜鸟级)

第一次写东西。虽有千言万语,确无法说出口!

首先新建一个工程,ADT或者Android Studio 工程都行。我使用的是ADT,因为Android Studio真的太大了,我的笔记本真心带不动啊。
xiaoguo
一 工程目录如下
这里写图片描述

注意到工程libs目录下的两个jar包
android-async-http-1.4.9.jar和httpclient-4.3.6.jar是需要从网上下载的,地址:http://loopj.com/android-async-http/
http://mvnrepository.com/artifact/cz.msebera.android/httpclient/4.3.6
下载完毕后导入到自己的libs目录下,分别右击–>Build path –>add to build path (Android studio 下 右击 Add as Library就行了)。
这个例子仅仅是演是如何下载一个图片和如何得到Json数据
XML文件

<LinearLayout 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"
    android:orientation="vertical"
    >

   <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
        android:id="@+id/btnDownLoad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载文件" />

        <Button
        android:id="@+id/btnJson"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Json解析" />
    </LinearLayout>

    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/ic_launcher"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textview"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="json数据"/>

    </ScrollView>


</LinearLayout>

还要在AndroidManifest.xml文件中添加访问网络的权限

<uses-permission android:name="android.permission.INTERNET" />

下载图片的方法

/**从服务器下载文件,这个方法用来下载一个图片
     * @param imgUrl
     *  String imgUrl="https://img-my.csdn.net/uploads/201309/01/1378037178_9374.jpg";

     */
    private void downLoadFile(String imgUrl) {

        //初始化一个client用来向服务器上传
        AsyncHttpClient client=new AsyncHttpClient();

        client.get(imgUrl, new BinaryHttpResponseHandler() {

            @Override
            public void onSuccess(int resultCode, Header[] arg1, byte[] response) {
                //下载成功
                imageView.setImageBitmap(decodeBitmapFromByteArray(response, imageView.getWidth(), imageView.getHeight()));


            }

            @Override
            public void onFailure(int resultCode, Header[] arg1, byte[] response, Throwable arg3) {
                //下载失败
                Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_LONG).show();

            }
        });
    }

/这加载图片的方法/

/**使用这个方法,首先你要将BitmapFactory.Options的inJustDecodeBounds属性设置为true,解析一次图片。
     * 然后将BitmapFactory.Options连同期望的宽度和高度一起传递到到calculateInSampleSize方法中,
     * 就可以得到合适的inSampleSize值了。之后再解析一次图片,使用新获取到的inSampleSize值,
     * 并把inJustDecodeBounds设置为false,就可以得到压缩后的图片了。
     * @param bytes
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public  Bitmap decodeBitmapFromByteArray(byte[]bytes, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes,0,bytes.length, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return  BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    }
    /**计算压缩比
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public  int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

获得json的请求方法

 /**get方式请求数据
     * @param jsonUrl
     *          String JsonUrl="http://api.k780.com:88/?app=weather.today&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

     */
    private void ParseJson(String jsonUrl) {

        //初始化一个client用来向服务器上传
            AsyncHttpClient client=new AsyncHttpClient();
            client.get(jsonUrl, new JsonHttpResponseHandler(){

                //返回JSONObject
                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        JSONObject response) {
                    try {
                        String s=response.toString();
                        textView.setText(s);

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    super.onSuccess(statusCode, headers, response);
                }
                //返回Json数组
                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        JSONArray response) {
                    // TODO Auto-generated method stub
                    super.onSuccess(statusCode, headers, response);
                }
            });

    }
/**
     * 模拟的一个上传文件的方法,真实使用的时候需要传过来一个真实的url和你想要上传的文件
     */
    private void UpLoadeFile(String url,File file) {

        //初始化一个client用来向服务器上传
        AsyncHttpClient client=new AsyncHttpClient();
        RequestParams params=new RequestParams();
        try {
            params.put("filename", file);//上传的文件名和文件
            client.post(url, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int resultCode, Header[] arg1, byte[] response) {

                    //上传成功,可以得到服务器返回的信息response
                }

                @Override
                public void onFailure(int resultCode, Header[] arg1, byte[] response, Throwable arg3) {

                    //上传失败,可以得到服务器返回的信息response
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

关于更多的Android async-http 的用法请参考以下网址
http://www.open-open.com/lib/view/open1433399000994.html

总结:我是一个android小菜鸟,不过我相信总有一天,我能独自一人搏击万里长空,俯瞰苍茫大地。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值