android okGo、okHttp、XUtils网络框架使用

代码结构


一、XUtils网络框架使用

1、先导入xutils的library库,然后在build.gradle中添加下面代码

 //xutils
    compile project(':xutils')

2、需要先在Application中初始化

 x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
3、实现请求普通数据

 /**
     * XUtils普通数据请求
     *
     */
    public void xUtilsOrdinary(){

        RequestParams params = new RequestParams(Api.TEST_URL);
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                ixUtilsPresenter.XUtilsSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ixUtilsPresenter.XUtilsError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

4、view代码

package com.example.apple.http.presenter;

import android.graphics.drawable.Drawable;

/**
 * Created by apple on 17/3/20.
 */

public interface IXUtilsPresenter {

    /**
     * 网络请求错误
     * @param msg
     */
    void XUtilsError(String msg);

    /**
     * 网络请求成功
     * @param msg
     */
    void XUtilsSuccess(String msg);

    /**
     * 返回图片数据
     * @param bitmap
     */
    void XUtilsBitmap(Drawable bitmap);
}

二、okHttp网络框架使用,这里主要实现简单的数据请求、bitamap图片请求、文件下载功能,推荐使用

1、先在build.gradle中添加

//okhttp
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    compile 'com.zhy:okhttputils:2.6.2'
    compile 'com.squareup.okio:okio:1.6.0'
2、实现代码

package com.example.apple.http.presenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import com.example.apple.http.utils.Api;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

/**
 * Created by apple on 17/3/20.
 */

public class OkHttpPresenter {

    private Context context;
    private IOkHttpPresenter iOkHttpPresenter;

    public OkHttpPresenter(Context context, IOkHttpPresenter iOkHttpPresenter) {
        this.context = context;
        this.iOkHttpPresenter = iOkHttpPresenter;
    }

    /**
     * okHttp网络请求
     */
    public void okHttp(){

        OkHttpUtils.get()
                .url(Api.TEST_URL)
                .id(100)
                .build()
                .execute(new com.zhy.http.okhttp.callback.StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        iOkHttpPresenter.okError(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        iOkHttpPresenter.okSuccess(response);
                    }
                });


    }

    /**
     * 请求网络图片
     */
    public void okHttpBitmap(){
        OkHttpUtils.get()
                .url(Api.TEST_BITMAP_URL)
                .tag(this)
                .build()
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        iOkHttpPresenter.okError(e.getMessage());
                    }

                    @Override
                    public void onResponse(Bitmap response, int id) {
                        iOkHttpPresenter.okBitmap(response);
                    }
                });

    }


    /**
     * 请求文件
     */
    public void okHttpFile(){
        OkHttpUtils.get()
                .url(Api.TEST_FILE_URL)
                .tag(this)
                .build()
                .execute(new FileCallBack("/sdcard/temp/", "file.rar") {文件下载时,需要指定下载的文件目录和文件名
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        iOkHttpPresenter.okError(e.getMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        iOkHttpPresenter.okFile(response);
                    }
                });

    }


}

3、view代码

package com.example.apple.http.presenter;

import android.graphics.Bitmap;

import java.io.File;

/**
 * Created by apple on 17/3/20.
 */

public interface IOkHttpPresenter {

    /**
     * 请求成功
     * @param msg
     */
    void okSuccess(String msg);

    /**
     * 请求错误
     * @param msg
     */
    void okError(String msg);

    /**
     * 请求网络图片
     * @param bitmap
     */
    void okBitmap(Bitmap bitmap);

    /**
     * 请求文件
     * @param msg
     */
    void okFile(File msg);

}

三、okGo使用,推荐使用

1、先在build.gradle中添加

//okGo
    compile 'com.lzy.net:okgo:+'        //版本号使用 + 可以自动引用最新版
    compile 'com.lzy.net:okrx:+'        //RxJava扩展支持 基于RxJava和RxAndroid的扩展,如果不需要可以不必引入
    compile 'com.lzy.net:okserver:+'    //下载管理和上传管理扩展

2、在application中添加

 //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文
        headers.put("commonHeaderKey2", "commonHeaderValue2");
        HttpParams params = new HttpParams();
        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
        params.put("commonParamsKey2", "这里支持中文参数");
        //-----------------------------------------------------------------------------------//


        //必须调用初始化
        OkGo.init(this);

        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            //以下都不是必须的,根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
            OkGo.getInstance()

                    //打开该调试开关,控制台会使用 红色error 级别打印log,并不是错误,是为了显眼,不需要就不要加入该行
                    .debug("OkGo")

                    //如果使用默认的 60秒,以下三行也不需要传
                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS)  //全局的连接超时时间
                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间

                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                    .setCacheMode(CacheMode.NO_CACHE)

                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)

                    //如果不想让框架管理cookie,以下不需要
//                .setCookieStore(new MemoryCookieStore())                //cookie使用内存缓存(app退出后,cookie消失)
                    .setCookieStore(new PersistentCookieStore())          //cookie持久化存储,如果cookie不过期,则一直有效

                    //可以设置https的证书,以下几种方案根据需要自己设置,不需要不用设置
//                    .setCertificates()                                  //方法一:信任所有证书
//                    .setCertificates(getAssets().open("srca.cer"))      //方法二:也可以自己设置https证书
//                    .setCertificates(getAssets().open("aaaa.bks"), "123456", getAssets().open("srca.cer"))//方法三:传入bks证书,密码,和cer证书,支持双向加密

                    //可以添加全局拦截器,不会用的千万不要传,错误写法直接导致任何回调不执行
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        return chain.proceed(chain.request());
//                    }
//                })

                    //这两行同上,不需要就不要传
                    .addCommonHeaders(headers)                                         //设置全局公共头
                    .addCommonParams(params);                                          //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }

3、实现代码

package com.example.apple.http.presenter;

import android.content.Context;
import android.graphics.Bitmap;

import com.example.apple.http.utils.Api;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 17/3/20.
 */

public class HttpPresenter {

    private Context context;
    private IHttpView iHttpView;
    private final String TAG = "HttpPresenter";

    public HttpPresenter(Context context, IHttpView iHttpView) {
        this.context = context;
        this.iHttpView = iHttpView;
    }


    /**
     * okgo 普通网络请求
     */
    public void okGoOrdinary() {

        OkGo.get(Api.TEST_URL)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .cacheKey("cacheKey")            // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
                .cacheMode(CacheMode.DEFAULT)    // 缓存模式,详细请看缓存介绍
                .execute(new StringCallback() {
                    /**
                     * 网络请求成功
                     * @param s
                     * @param call
                     * @param response
                     */
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        // s 即为所需要的结果
                        iHttpView.httpSuccess("网络请求成功!");
                        iHttpView.httpData(response);
                    }

                    /**
                     * 网络请求错误
                     * @param call
                     * @param response
                     * @param e
                     */
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                        iHttpView.httpError(e.getMessage());

                    }
                });
    }

    /**
     * 请求下载网络图片
     */
    public void okGoBitmap() {

        OkGo.get(Api.TEST_BITMAP_URL)
                .tag(this)//
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Bitmap bitmap, Call call, Response response) {
                        // bitmap 即为返回的图片数据
                        iHttpView.httpSuccess("数据返回成功");
                        iHttpView.httpBitmap(bitmap);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                        iHttpView.httpError(e.getMessage());
                    }
                });
    }

    /**
     * 请求文件下载
     */
    public void okGoFile(){
        OkGo.get(Api.TEST_FILE_URL)//
                .tag(this)//
                .execute(new FileCallback("file.jpg") {  //文件下载时,需要指定下载的文件目录和文件名
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        // file 即为文件数据,文件保存在指定目录
                        iHttpView.httpSuccess("数据返回成功");
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        //这里回调下载进度(该回调在主线程,可以直接更新ui)
                        iHttpView.httpFileProgress(progress);
                    }
                });
    }


  

4、view代码实现

package com.example.apple.http.presenter;

import android.graphics.Bitmap;

import okhttp3.Response;

/**
 * Created by apple on 17/3/20.
 */

public interface IHttpView {

    /**
     * 网络请求错误
     * @param msg
     */
    void httpError(String msg);

    /**
     * 网络请求成功
     * @param msg
     */
    void httpSuccess(String msg);

    /**
     * 网络请求返回的数据
     * @param msg
     */
    void httpData(Response msg);

    /**
     * 返回的图片数据
     * @param bitmap
     */
    void httpBitmap(Bitmap bitmap);

    /**
     *  下载进度
     * @param progress
     */
    void httpFileProgress(float progress);
}
四、请求的url,文件图片等可以自己到七牛注册一个帐号,然后上传上去,拿来测试

package com.example.apple.http.utils;

/**
 * Created by apple on 17/3/20.
 */

public class Api {
    public static final String TEST_URL = "http://112.124.22.238:8081/course_api/wares/hot?pageSize=10&curPage=1";

    public static final String TEST_BITMAP_URL = "http://7mno4h.com2.z0.glb.qiniucdn.com/s_recommend_55c1e8f7N4b99de71.jpg";

    public static final String TEST_FILE_URL = "http://omoml61n3.bkt.clouddn.com/Android%E5%BA%94%E7%94%A8%E6%BA%90%E7%A0%81%E9%9F%B3%E4%B9%90%E5%AE%9E%E6%97%B6%E8%B7%B3%E5%8A%A8%E9%A2%91%E8%B0%B1%E6%98%BE%E7%A4%BA.rar";
}
五、app的布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.apple.http.activity.MainActivity">

    <Button
        android:id="@+id/okgo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="okgo" />

    <Button
        android:id="@+id/XUtils"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="XUtils" />

    <Button
        android:id="@+id/volley"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="volley" />

    <Button
        android:id="@+id/okHttp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="okHttp" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
mainActivity实现代码

package com.example.apple.http.activity;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.apple.http.R;
import com.example.apple.http.presenter.HttpPresenter;
import com.example.apple.http.presenter.IHttpView;
import com.example.apple.http.presenter.IOkHttpPresenter;
import com.example.apple.http.presenter.IXUtilsPresenter;
import com.example.apple.http.presenter.OkHttpPresenter;
import com.example.apple.http.presenter.XUtilsPresenter;
import com.lzy.okgo.OkGo;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements IHttpView ,IOkHttpPresenter,IXUtilsPresenter{

    /**
     * http://blog.csdn.net/u011324501/article/details/53933212 volley使用
     */

    @BindView(R.id.okgo)
    Button okgo;
    @BindView(R.id.XUtils)
    Button XUtils;
    @BindView(R.id.volley)
    Button volley;
    @BindView(R.id.okHttp)
    Button okHttp;
    @BindView(R.id.image)
    ImageView image;

    private HttpPresenter httpPresenter;
    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        httpPresenter = new HttpPresenter(this, this);

    }

    @OnClick({R.id.okgo, R.id.XUtils, R.id.volley, R.id.okHttp})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.okgo://okGo

                 httpPresenter.okGoOrdinary();//普通数据请求
                // httpPresenter.okGoBitmap();//网络图片请求
                //httpPresenter.okGoFile();//网络文件下载

                break;
            case R.id.XUtils://XUtils

                XUtilsPresenter xUtilsPresenter = new XUtilsPresenter(this,this);
                xUtilsPresenter.xUtilsOrdinary();
               // xUtilsPresenter.xUtilsBitmap();
                break;
            case R.id.volley:

                break;
            case R.id.okHttp://okHttp
                OkHttpPresenter okHttpPresenter = new OkHttpPresenter(this,this);
                //okHttpPresenter.okHttp();
               // okHttpPresenter.okHttpBitmap();
                okHttpPresenter.okHttpFile();

                break;
        }
    }

    @Override
    public void httpError(String msg) {
        Toast.makeText(getApplication(), "msg=" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void httpSuccess(String msg) {
        Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void httpData(Response msg) {
        Log.e(TAG, "msg=" + msg);
    }

    @Override
    public void httpBitmap(Bitmap bitmap) {
        image.setImageBitmap(bitmap);
    }

    @Override
    public void httpFileProgress(float progress) {
        okgo.setText(progress * 100 + "%");

        if (progress == 1.0) {
            okgo.setText("okGo");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //根据 Tag 取消请求
        OkGo.getInstance().cancelTag(this);
    }


    /**
     * okHttp
     * @param msg
     */
    @Override
    public void okSuccess(String msg) {
        Toast.makeText(getApplication(), "msg=" + msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * okHttp
     * @param msg
     */
    @Override
    public void okError(String msg) {
        Toast.makeText(getApplication(), "msg=" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void okBitmap(Bitmap bitmap) {
        image.setImageBitmap(bitmap);
    }

    @Override
    public void okFile(File msg) {
        Toast.makeText(getApplication(), "msg=" + msg.getName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void XUtilsError(String msg) {
        Toast.makeText(getApplication(), "msg=" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void XUtilsSuccess(String msg) {
        Toast.makeText(getApplication(), "msg=" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void XUtilsBitmap(Drawable bitmap) {
        image.setImageDrawable(bitmap);
    }
}

最后记得加上权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.apple.http">

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

    <application
        android:allowBackup="true"
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


okgo使用详解:http://www.jianshu.com/p/4c17956fe3b4

okhttp使用详解:http://blog.csdn.net/lmj623565791/article/details/47911083

volley使用:http://blog.csdn.net/u011324501/article/details/53933212

xUtils详细使用:自己找

demo代码:http://download.csdn.net/detail/u011324501/9787917

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值