前言:

通过本篇,能够精晓一下几点:

  • Android中网络要求进化
  • okhttp是什么
  • okhttp的粗略利用

要是有野趣,能够看下我的另一篇,okhttp的大致包装:

网络乞求发展:

  • HttpURLConnection—>Apache HTTP
    Client—>Volley—->okHttp

OkHttp是什么:

  • 品种开源地址 :
  • 种类利用:在build.gradle中参预信赖
    compile 'com.squareup.okhttp3:okhttp:3.0.1'

OkHttp是一个飞速的HTTP库:

  • 1.帮助 SPDY ,分享同三个Socket来管理同一个服务器的持有乞求
  • 2.一旦SPDY不可用,则经过连接池来压缩伏乞延时
  • 3.无缝的支撑GZIP来收缩多少流量
  • 4.缓存响应数据来裁减重复的网络央浼

优点:

  • OkHttp会从相当多常用的连接难题中活动还原。假让你的服务器配置了多少个IP地址,当第贰个IP连接退步的时候,会自动尝试下四个IP。OkHttp还管理了代理服务器难题和SSL握手战败难题。
  • 利用 OkHttp
    无需重写你程序中的互连网代码。OkHttp达成了大概和java.net.HttpU科雷傲LConnection同样的API。假使你用了
    Apache HttpClient,则OkHttp也提供了三个应和的okhttp-apache 模块

  • 1.Get请求
  • 2.POST乞请表单(key-value)
  • 3.POST伸手提交(JSON/String/文件等)
  • 4.文书下载
  • 5.乞求超时设置

 OkHttpClient client=new OkHttpClient(); Request request = new Request.Builder().url .build(); Response response= client.newCall.execute(); String message=response.body().string();

 OkHttpClient client=new OkHttpClient(); Request request = new Request.Builder().url.build(); client.newCall.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { } });

在这里解释一下,笔者在用3.0的时候,去找FormEncodingBuilder(),那个点子,找不到了,就去了她的官方网站查阅了信息,找到了刹那间一段解释:

  • We’ve replaced the opaque FormEncodingBuilder with the more powerful
    FormBody and FormBody.Builder combo. Similarly we’ve upgraded
    MultipartBuilder into MultipartBody, MultipartBody.Part, and
    MultipartBody.Builder.

okhttp3.0之前:

 OkHttpClient client = new OkHttpClient(); RequestBody forBody = new FormEncodingBuilder().add("username","tom").add("password", "1110").build(); Request request=new Request.Builder().url.post.build(); client.newCall.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { Log.d("xiaoming",response.body().string; 

okhttp3.0之后

 OkHttpClient client = new OkHttpClient(); FormBody formBody = new FormBody.Builder() .add("type", "1") .build(); Request request=new Request.Builder().url.post.build(); client.newCall.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { Log.d("xiaoming",response.body().string; 

 String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg"; //构建request对象 Request request = new Request.Builder().url.build(); OkHttpClient client = new OkHttpClient(); client.newCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { InputStream inputStream = response.body().byteStream(); FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/logo.jpg")); byte[] buffer = new byte[2048]; int len = 0; while ((len = inputStream.read != -1) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.flush(); Log.d("wuyinlei", "文件下载成功..."); } });

okhttp3.0之前:

 client.setConnectTimeout(10, TimeUnit.SECONDS); client.setWriteTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS);

okhttp3.0之后:

 client.newBuilder().connectTimeout(10, TimeUnit.SECONDS); client.newBuilder().readTimeout(10,TimeUnit.SECONDS); client.newBuilder().writeTimeout(10,TimeUnit.SECONDS);

下面看下结果演示:

图片 1此间写图片描述

注:不知晓为什么,作者的写入sdcard的权限也加了,正是引玉之砖小编下载的时候从不权力,作者只得用真机了,这里通过log日志来申报下载成功:

图片 2

下边来看下代码,布局极粗略,多个开关,八个textview,这里就不解释了

package com.example.okhttpdemo;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.TextView;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.concurrent.TimeUnit;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button syncGet; private Button asyncget; private Button post; private Button fileDownload,fengzhuang; private TextView tvtext; private String result; private OkHttpClient client; /** * 在这里直接设置连接超时,初始化OkHttpClient */ private void init() { client = new OkHttpClient(); client.newBuilder().connectTimeout(10, TimeUnit.SECONDS); client.newBuilder().readTimeout(10, TimeUnit.SECONDS); client.newBuilder().writeTimeout(10, TimeUnit.SECONDS); } private Request request; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); initialize(); initListener(); } /** * 事件监听 */ private void initListener() { syncGet.setOnClickListener; asyncget.setOnClickListener; post.setOnClickListener; fileDownload.setOnClickListener; fengzhuang.setOnClickListener; } /** * 初始化布局控件 */ private void initialize() { syncGet =  findViewById(R.id.syncGet); asyncget =  findViewById(R.id.asyncget); post =  findViewById(R.id.post); tvtext =  findViewById(R.id.tv_text); fileDownload =  findViewById(R.id.fileDownload); fengzhuang =  findViewById(R.id.fengzhuang); } @Override public void onClick { switch ) { case R.id.syncGet: initSyncData(); break; case R.id.asyncget: initAsyncGet(); break; case R.id.post: initPost(); break; case R.id.fileDownload: downLoadFile(); break; case R.id.fengzhuang: break; } } /** * get请求同步方法 */ private void initSyncData() { new Thread(new Runnable() { @Override public void run() { try { request = new Request.Builder().url(Contants.SYNC_URL).build(); Response response = client.newCall.execute(); result = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { tvtext.setText; Log.d("MainActivity", "hello"); } }); } catch (Exception e) { e.printStackTrace.start(); } /** * 异步请求 */ private void initAsyncGet() { new Thread(new Runnable() { @Override public void run() { request = new Request.Builder().url(Contants.ASYNC_URL).build(); client.newCall.enqueue(new Callback() { /** * A call is a request that has been prepared for execution. A call can be canceled. As this object * represents a single request/response pair , it cannot be executed twice. * * * @param call 是一个接口, 是一个准备好的可以执行的request * 可以取消,对位一个请求对象,只能单个请求 * @param e */ @Override public void onFailure(Call call, IOException e) { Log.d("MainActivity", "请求失败"); } /** * * @param call * @param response 是一个响应请求 * @throws IOException */ @Override public void onResponse(Call call, Response response) throws IOException { /** * 通过拿到response这个响应请求,然后通过body().string(),拿到请求到的数据 * 这里最好用string() 而不要用toString() * toString()每个类都有的,是把对象转换为字符串 * string()是把流转为字符串 */ result = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { tvtext.setText; } }); } }); } }).start(); } /** * 表单提交 */ private void initPost() { String url = "http://112.124.22.238:8081/course_api/banner/query"; FormBody formBody = new FormBody.Builder() .add("type", "1") .build(); request = new Request.Builder().url .post.build(); new Thread(new Runnable() { @Override public void run() { client.newCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, final Response response) throws IOException { runOnUiThread(new Runnable() { @Override public void run() { tvtext.setText; } }); } }); } }).start(); } /** * 文件下载地址 */ private void downLoadFile() { String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg"; request = new Request.Builder().url.build(); OkHttpClient client = new OkHttpClient(); client.newCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //把请求成功的response转为字节流 InputStream inputStream = response.body().byteStream(); /** * 在这里要加上权限 在mainfests文件中 * <uses-permission android:name="android.permission.INTERNET"/> * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> */ //在这里用到了文件输出流 FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/logo.jpg")); //定义一个字节数组 byte[] buffer = new byte[2048]; int len = 0; while ((len = inputStream.read != -1) { //写出到文件 fileOutputStream.write(buffer, 0, len); } //关闭输出流 fileOutputStream.flush(); Log.d("wuyinlei", "文件下载成功..."); } }); }}

好了,轻松的okhttp使用就介绍到此地了,接下去会对其达成以下简单的卷入。

是因为okhttp3.0较于事先的略微变化,大家使用的时候能够去看下他们官方的证实,这样在利用中就能够少了不供给的辛劳了。

1.get请求:

       
现在市情上相比热暑的Android互连网框架,就小编知道的,volley,okhttp,retrofit+rxjava,当然rxjava不到底互联网框架,只是合作retofit使用特别便利,volley是自笔者动用得比较多的一个互联网框架,可是用她来做轻量的数目央浼自是没难题,可是在下载和上传文件上,仿佛就能够暴光一些难点,啥难题自身也不知情,因为本身只是菜鸟,这几个事物也是三个协和的知晓,倘若有荒唐的地点,勿喷。

那是二个互联网供给的框架,接下去介绍怎么样利用,不说原理,直说怎么利用

0.前言

近日的Escortxjava+retrofit+okhttp+mvp十二分刚强,小编也遗弃了原先的框架,加入到PRADOx大军在那之中,在网络上翻找了一大推资料,看过多数学科文章,Crach很数十次,未来才勉强搭建出团结的小框架,以登入为小例子,上边给咱们轻松地讲学下一切框架的贯彻流程。

/**
 *
 *okhttp get请求
 * */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * 创建okhttpClient对象
         * */
        OkHttpClient mOkHttpClient = new OkHttpClient();
        /**
         *创建Request对象
         **/
        final Request request = new Request.Builder()
                .url("http://v.juhe.cn/toutiao/index?type=top&key=3f8238bb55566d2b3f0d2204a5e9631f")
                .build();
        /**
         * new Call
         * */
        Call call = mOkHttpClient.newCall(request);

        /**
         * 请求调度
         * */
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String htmlStr =  response.body().string();
                Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + htmlStr + "]");
            }
        });
    }
}

        
下边就踏入正题,本来作者是想利用retrofit,但是我又想一口吃成胖子,对于rxjava的读书上拦截,所以转战okhttp,以下则是作者对okhttp的部分明白和使用:

1.凭仗注入

 compile 'com.squareup.okhttp:okhttp:2.4.0'
 compile 'com.google.code.gson:gson:2.6.2'

1.导包

其一导包必需注意一点,被坑了重重次,因为他版本号须要平等,否则会报些古怪的错误

//retrofit和rxjava  使用所需导的包  
compile'com.squareup.retrofit2:retrofit:2.0.0-beta3'    
compile'io.reactivex:rxjava:1.0.1'    
compile'io.reactivex:rxandroid:1.0.1'    
compile'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'    //用于Retroid设置addCallAdapterFactory
compile'com.squareup.retrofit2:converter-scalars:2.0.0-beta4' //用于Retroid设置addConverterFactory,这个是String转换,总共有7个选择,有Gson,XML等等,根据自己需要导入
compile'com.squareup.okhttp3:okhttp:3.3.1'    
compile'com.squareup.okhttp3:logging-interceptor:3.3.1'        //OKHTTP设置日志级别

2,post请求:

          因为笔者用的是Android Studio,所以率先重视

2.提供四个HttpUtils的封装类

package com.wocus.myapplication.util;

import android.os.Handler;
import android.os.Looper;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2017/8/15.
 * Author:crs
 * Description:网络请求工具类的封装
 */
public class HttpUtils {

    private OkHttpClient client;
    private Handler mHandler;

    public HttpUtils() {
        client = new OkHttpClient();
        //设置连接超时时间,在网络正常的时候有效
        client.setConnectTimeout(30*1000, TimeUnit.SECONDS);
        //设置读取数据的超时时间
        client.setReadTimeout(30*1000, TimeUnit.SECONDS);
        //设置写入数据的超时时间
        client.setWriteTimeout(30*1000, TimeUnit.SECONDS);

        //Looper.getMainLooper()  获取主线程的消息队列
        mHandler = new Handler(Looper.getMainLooper());
    }




    public void get(String url, BaseCallBack baseCallBack) {
        Request request = buildRequest(url, null, HttpMethodType.GET);
        sendRequest(request, baseCallBack);
    }


    public void post(String url, HashMap<String,String> params, BaseCallBack baseCallBack) {
        Request request = buildRequest(url, params, HttpMethodType.POST);
        sendRequest(request, baseCallBack);

    }

    /**
     * 1)获取Request对象
     *
     * @param url
     * @param params
     * @param httpMethodType 请求方式不同,Request对象中的内容不一样
     * @return Request 必须要返回Request对象, 因为发送请求的时候要用到此参数
     */
    private Request buildRequest(String url, HashMap<String, String> params, HttpMethodType httpMethodType) {
        //获取辅助类对象
        Request.Builder builder = new Request.Builder();
        builder.url(url);

        //如果是get请求
        if (httpMethodType == HttpMethodType.GET) {
            builder.get();
        } else {
            RequestBody body = buildFormData(params);
            builder.post(body);
        }

        //返回请求对象
        return builder.build();
    }

    /**
     * 2)发送网络请求
     *
     * @param request
     * @param baseCallBack
     */
    private void sendRequest(Request request, final BaseCallBack baseCallBack) {
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                callBackFail(baseCallBack,request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    //此时请求结果在子线程里面,如何把结果回调到主线程里?
                    callBackSuccess(baseCallBack,response, json);
                } else {
                    callBackError(baseCallBack,response, response.code());
                }
            }
        });
    }


    /**
     * 主要用于构建请求参数
     *
     * @param param
     * @return ResponseBody
     */
    private RequestBody buildFormData(HashMap<String,String> param) {

        FormEncodingBuilder builder = new FormEncodingBuilder();
        //遍历HashMap集合
        if (param != null && !param.isEmpty()) {
            Set<Map.Entry<String, String>> entries = param.entrySet();
            for (Map.Entry<String, String> entity : entries) {
                String key = entity.getKey();
                String value = entity.getValue();
                builder.add(key, value);
            }
        }
        return builder.build();
    }

    //请求类型定义
    private enum HttpMethodType {
        GET,
        POST
    }

    //定义回调接口
    public interface BaseCallBack {
        void onSuccess(Response response, String json);

        void onFail(Request request, IOException e);

        void onError(Response response, int code);
    }



    //主要用于子线程和主线程进行通讯
   private void callBackSuccess(final BaseCallBack baseCallBack, final Response response, final String json){
       mHandler.post(new Runnable() {
           @Override
           public void run() {
               baseCallBack.onSuccess(response,json);
           }
       });
   }


    private void callBackError(final BaseCallBack baseCallBack, final Response response, final int code){
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                baseCallBack.onError(response,code);
            }
        });
    }

    private void callBackFail(final BaseCallBack baseCallBack, final Request request, final IOException e){
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                //相当于此run方法是在主线程执行的,可以进行更新UI的操作
                baseCallBack.onFail(request,e);
            }
        });
    }

}

2.权限

  • 在注册清单中加多网络权限

<uses-permission android:name="android.permission.INTERNET"/>
/**
 *
 * okhttp  post请求
 * */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    /**
     * 请求地址
     * */
    String URL = "这里为请求地址";
    JSONObject obj = new JSONObject();
    String sss;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * post请求体为json字符串
         * */
        try {
            obj.put("name", "123");
            obj.put("pwd", "456");
            sss = obj.toString();
            post(URL, sss);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   public void post(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString() );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Log.i(TAG, "onResponse*: "+response.body().string());
            }
        });


    }
}

compile’com.squareup.okhttp3:okhttp:3.4.2′

3.再提供三个gson的封装类

    package com.wocus.myapplication.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class GsonUtil {
    private static Gson gson = null;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    private GsonUtil() {
    }

    /**
     * 转成json
     *
     * @param object
     * @return
     */
    public static String GsonString(Object object) {
        String gsonString = null;
        if (gson != null) {
            gsonString = gson.toJson(object);
        }
        return gsonString;
    }

    /**
     * 转成bean
     *
     * @param gsonString
     * @param cls
     * @return
     */
    public static <T> T GsonToBean(String gsonString, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * 转成list
     * 泛型在编译期类型被擦除导致报错
     *
     * @param gsonString
     * @param cls
     * @return
     */
    public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
        List<T> list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
            }.getType());
        }
        return list;
    }

    /**
     * 转成list
     * 解决泛型问题
     *
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public <T> List<T> jsonToList(String json, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }


    /**
     * 转成list中有map的
     *
     * @param gsonString
     * @return
     */
    public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
        List<Map<String, T>> list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString,
                    new TypeToken<List<Map<String, T>>>() {
                    }.getType());
        }
        return list;
    }

    /**
     * 转成map的
     *
     * @param gsonString
     * @return
     */
    public static <T> Map<String, T> GsonToMaps(String gsonString) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }

}

3.类型布局

图片 3

品类组织

职业的MVP架构,这里对MVP就不多说,MVP的逻辑相比较简单,主要考虑就是经过接口完成各种层之间的解耦。

 3.okhttp下载文件

  ,信赖完之后就足以选择了,首先:

4.呼吁网络利用

package com.wocus.myapplication.activity

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.squareup.okhttp.Request
import com.squareup.okhttp.Response
import com.wocus.myapplication.R
import com.wocus.myapplication.util.GsonUtil
import com.wocus.myapplication.util.HttpUtils
import com.wocus.myapplication.util.SUtils
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException


/**
 * 登录界面
 */
class MainActivity : AppCompatActivity(), View.OnClickListener ,HttpUtils.BaseCallBack{

    var load_dialog: ProgressDialog?=null

    override fun onSuccess(response: Response?, json: String?) {
        Log.d("TAG","请求成功"+json)
        load_dialog!!.dismiss()
        var modelbean: MutableMap<String, String>? =GsonUtil.GsonToMaps<String>(json)
        if (modelbean!!["code"].toString() == "1") {
            startActivity(Intent(this, IndexActivity::class.java))
            Toasty.success(this, "登录成功").show()
        }else{
            Toasty.error(this,modelbean.get("msg").toString())
        }
    }
    override fun onFail(request: Request?, e: IOException?) {
        load_dialog!!.dismiss()
        Toasty.error(this,"网络连接超时").show()
    }

    override fun onError(response: Response?, code: Int) {
        load_dialog!!.dismiss()
        Toasty.error(this, "服务器发生错误").show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_login_login.setOnClickListener(this)
        load_dialog=SUtils().initDialog(this)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.btn_login_login->
                if(edt_login_account.text.trim().length<=0){
                    Toasty.info(this,"请输入账号").show()
                    YoYo.with(Techniques.Tada).duration(500).playOn(layout_login_account)
                    return
                }else if(edt_login_password.text.trim().length<=0){
                    Toasty.info(this,"请输入密码").show()
                    YoYo.with(Techniques.Tada).duration(500).playOn(layout_login_pwd)
                    return
                }else{
                     load_dialog!!.show()
                    startActivity(Intent(this, IndexActivity::class.java))
                    var map:HashMap<String,String>?= HashMap()
                    map!!.put("account",edt_login_account.text.toString())
                    map.put("password",edt_login_account.text.toString())
                   HttpUtils().post("http://192.168.0.117:8080/Shopnert/login.do",map,this)
                }
        }
    }
}

4.OkHttp与Retrofit的配置与简单利用

  1. 建立ApiService.class

/**
  *配置请求参数的接口
*/
public interface ApiService 
{   
     @GET("webservice/Base/UserInfo.asmx/Login6")   //GET请求
     Observable<String> logining(@Query("username") String username, @Query("password") String password);  //传入username 、password两个参数.
}

那边你须求学习Retrofit的操作符,才可以灵活运用起来,这里举个简易的get乞请的例证

  1. 建立Api.class

1.配置OKhttp(设置央浼超时时间,配置诉求尾部新闻。。。等)。
2.布署Retrofit(关联OkHttp,添扩张少调换器,加多Base的U本田UR-VL。。。等)
3.确立apiService,将Retrofit 与ApiService接口连接起来。
4.提供单例的retrofit的service。

public class Api {
    //单例模式获取ApiService
    private volatile static Api INSTANCE;
    private final ApiService apiService;
    //头部验证信息
    Interceptor headerInterceptor =new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request build = chain.request().newBuilder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")//配置头部信息
                    .build();
            return chain.proceed(build);
        }
    };

    private Api(){
        //配置OKhttp请求参数
        OkHttpClient okHttp= new OkHttpClient.Builder()
                .readTimeout(7676, TimeUnit.MILLISECONDS)    
                .connectTimeout(7676, TimeUnit.MILLISECONDS)
                .addInterceptor(headerInterceptor)    //添加头部信息
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                //关联OKhttp
                .client(okHttp)
                //设置请求回来的数据为Gson
                //.addConverterFactory(GsonConverterFactory.create())
                //设置service接口可以作为Observable返回
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //设置请求回来的数据为String,可以添加其他的适配器Gson.xml等7种,自动转化
                .addConverterFactory(ScalarsConverterFactory.create())
                //添加基础url
                .baseUrl("http://"+"192.168.10.66:8081/")
                .build();
         //建立apiService
        apiService = retrofit.create(ApiService.class);
    }

    /**
     * 单例模式获取网络请求基类retrofit的service
     * @return 单例ApiService
     */
    public static ApiService getInstance() {
        if (INSTANCE == null) {
            synchronized (Api.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Api();
                }
            }
        }
        return INSTANCE.apiService;
    }
}

 

private OkHttpClient okHttpClient;

private Request request;

private Call call;

呼吁网络就到此地,接下去使用okhttp完结下载,提供四个okhttp下载包装工具类

package com.wocus.myapplication.util;

import android.os.Environment;
import android.support.annotation.NonNull;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DownloadUtil {

    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * @param url 下载连接
     * @param saveDir 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(final String url, final String saveDir, final OnDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress
         * 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }
}

5.施用于轻便登录

图片 4

登陆UI

1.View层代码就不全贴出来了,都以简轻便单的分界面。只贴出点击登入的View层完结代码

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KLog.d("点击了登陆");
                mPresenter.login();   //调用P层的login方法
            }
        });

2.Presenter层的login方法完结代码如下

 @Override
    void login() {
        LoginModel loginModel = new LoginModel();//创建Model层的实类
        //调用Model层的loginGet方法
        //RxSubscriber是我自定的网络请求处理,不自己处理可以Subscriber即可。
        loginModel.loginGet(mView.getUserName(),mView.getPwd()).subscribe(new RxSubscriber<LoginUserBean>(mContext,true) {
            @Override
            protected void _onNext(LoginUserBean loginUserBean) {
                KLog.d("登陆成功");
            }

            @Override
            protected void _onError(String message) {
                KLog.d("登陆失败");
            }
        });
    }

3.Model层代码落成如下

public class LoginModel {
   //返回Observable,是为了给Presenter进行链式编程,可以监控成功失败
    public Observable<LoginUserBean> loginGet(String username, String pwd){
       //调用Api类获取serverce进行Apiservice定义的接口进行请求。
       //MyFunc1是我自定义的一个类型属于处理类,你也可以自定义该类进行数据的处理
        return Api.getInstance().logining(username,pwd).map(new MyFunc1<LoginUserBean>() {
            @Override
            public Class<LoginUserBean> setBeanClass() {
                return LoginUserBean.class;
            }
        }).subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread());
    }
}
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

因为无论是get央求,post哀告,照旧上传下载文件,都急需这八个,总不可能多个文件就新建叁个指标啊,然后本人在构造函数中实例化了

下载封装类的选择

DownloadUtil.get().download("http://192.168.0.117:8080/Shopnert/ShipCargo.apk", "download", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Toasty.error(getBaseContext(), "下载成功").show();
            }

            @Override
            public void onDownloading(int progress) {
                Toasty.error(getBaseContext(), "进度为" + progress).show();
            }

            @Override
            public void onDownloadFailed() {
                Toasty.error(getBaseContext(), "下载失败").show();
            }
        });

回顾利用就到那边。

6.总结

上述便是轻巧的本田UR-Vxjava+retrofit+okhttp+mvp使用,哪方面不是很明白,最棒是去读书该地点的篇章得到知识就可以。

上面提供部分民用认为有十分大的收获的稿子

1.Rxjava:
给 Android 开辟者的 MuranoxJava
详解。
关于奥迪Q5xJava最友好的篇章。
2.Retrofit
Retrofit用法详解
当Rxjava遇到Retrofit

 

public Http OkHttp() {

okHttpClient=new OkHttpClient();

}

 

,get须要如下:

/**
 *okhttp 下载文件
 *
 * */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    OkHttpClient mOkHttpClient=new OkHttpClient();
    /**
     * 请求地址
     * */
    String LOAD1="http://gdown.baidu.com/data/wisegame/baidusearch_Android_10189_1399k.apk" ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Request request = new Request.Builder().url(LOAD1).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString() );
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                try {
                    is = response.body().byteStream();
                    File file = new File(SDPath, "test.apk");
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    Log.d(TAG, "文件下载成功");
                } catch (Exception e) {
                    Log.d(TAG, "文件下载失败"+e.toString());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }





}

public Call getOkhttp() {

             request=new Request.Builder()

                                                      .url(url)

                                                      .build();

              call=okHttpClient.newCall(request);

              return call;

}

  1. okhttp上传文件

    /*
    okhttp 上传文件
    *

    • */
      public class MainActivity extends AppCompatActivity {

      private static final String TAG = “MainActivity”;

      /**

      • 呼吁地址
      • */
        String LOAD1=”” ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(SDPath, “test.apk”);
        RequestBody fileBody = RequestBody.create(MediaType.parse(“application/octet-stream”), file);
        RequestBody requestBody = new MultipartBody.Builder()

             .setType(MultipartBody.FORM)
             .addFormDataPart("myfile", "test.apk", fileBody)
             .build();
        

        Request request = new Request.Builder()

             .url(LOAD1)
             .post(requestBody)
             .build();
        

自家是把call直接回到出来,那样小编用着舒适些, 正规写法如下:

        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient  = httpBuilder
                /**
                 * 设置超时
                 * */
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "uploadMultiFile()11 e=" + e);
            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "uploadMultiFile() response11=" + response.body().string());
            }
        });
    }





}

public void getOkhttp() {

request=newRequest.Builder()

.url(url)

.build();

call=okHttpClient.newCall(request);

call.enqueue(new Callback() {

@Override

public void onFailure(Call call,IOException e) {

//这里面试须求错误调用

}

@Override

public void onResponse(Call call,Response response) throws
IOException{

//那是是伸手成功重临的

//获得重返消息则是 response.body().string()

}

});

}

 

,post央浼如下:

public Call postOkhttp(RequestBody requestBody) {

request=new Request.Builder()

.url(url)

.post(requestBody)

.build();

call=okHttpClient.newCall(request);

return call;

}

键值对自身是将其领抽出来,定义如下:

RequestBody requestBody=new FormBody.Builder()

.add(“key”,”valuse”)

.build();

add方准绳是往里面参加乞求体,使用依旧很简短的,

上传文件如下:

public Call FileOkhttp(String filename,String key) {

File file=new File(Environment.getExternalStorageDirectory(),
filename);

RequestBody
fileBody=RequestBody.create(MediaType.parse(“application/octet-stream”),file);

RequestBody requestBody=new MultipartBody.Builder()

                                                                                      
.setType(MultipartBody.FORM)

                                                                                      
.addPart(Headers.of(“Content-Disposition”,”form-data;
name=\”username\””),

                                                                                       
RequestBody.create(null, key))//上传文件名

                                                                                       
.addPart(Headers.of(“Content-Disposition”,”form-data;
name=\”mFile\”; filename =\”wjd.mp4\””),fileBody)

                                                                                        
.build();

request=new Request.Builder()

                                         .url(url)

                                          .post(requestBody)

                                           .build();

call=okHttpClient.newCall(request);

return call;

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图