美文网首页
OkHttp3基本使用

OkHttp3基本使用

作者: 吃荷包蛋 | 来源:发表于2018-03-29 16:15 被阅读0次
    导入
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.okio:okio:1.7.0'
    
    Get请求
            String url =  "https://www.baidu.com";
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d(TAG, "failure: ");
                    e.printStackTrace();
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, "RESPONSE RESULT:" + response.body().string());
                }
            });
    

    可以通过header、method设置更多的参数

    Request request = new Request.Builder()
                    .url(url)
                    .header("key","value")
                    .header("key","value")
                    .build();
    

    可以通过调用execute()执行同步方法,当然你必须得通过cancel()方法取消。
    OkHttp支持大文件下载,如果希望获得返回的二进制字节数组,则调用response.body().bytes();
    如果你想拿到返回的inputStream,则调response.body().byteStream()

       final File file = new File(Environment.getExternalStorageDirectory().toString() + "/default.png");
            String url = "http://35.185.149.228/static/user/images/default.jpg";;
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream os = null;
                    InputStream inputStream = null;
    
                    try {
                        inputStream = response.body().byteStream();
                        os = new FileOutputStream(file);
                        while ((len = inputStream.read(buf)) != -1) {
                            os.write(buf, 0, len);
                        }
                        os.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (os != null)
                            os.close();
                        if (inputStream != null)
                            inputStream.close();
                    }
                }
            });
    
    Post请求

    post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。
    1.普通表单application/x-www-form-urlencoded

    String url = "https://www.baidu.com";
            FormBody body = new FormBody.Builder()
                    .add("login_username", "jikexueyuanjgc")
                    .add("login_password", "123456")
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
    

    2.multipart/form-data 上传文件

    File file = new File(Environment.getExternalStorageDirectory() + "/ic_launcher.png");
    
    //不带参数的RequestBody
    //RequestBody body = RequestBody.create(MediaType.parse("image/png"),file);
    
    //带参数的RequestBody
    MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.addFormDataPart("filename", "testpng");
            builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
    
            RequestBody body = builder.build();
    

    3.application/json 数据是个json

    RequestBody body = RequestBody.create(MediaType.parse("aaplication/json;charset=utf-8"), "这是你的json串");
    
    自动管理Cookie

    通过设置header,上传Cookie

    Request request = new Request.Builder()
        .url(url)
        .header("Cookie", "xxx")
        .build();
    

    通过onRespone获取Cookie

     @Override
                public void onResponse(Call call, Response response) throws IOException 
                {
                    setCookieList = response.headers("Set-Cookie");
                    Log.i(TAG, "repose result:  " + response.body().string());
                }
    

    但是okhttp可以不用我们管理Cookie,自动携带,保存和更新Cookie。
    方法是在创建OkHttpClient设置管理Cookie的CookieJar

    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                cookieStore.put(httpUrl.host(), list);
            }
    
            @Override
            public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                List<Cookie> cookies = cookieStore.get(httpUrl.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        })
        .build();
    

    相关文章

      网友评论

          本文标题:OkHttp3基本使用

          本文链接:https://www.haomeiwen.com/subject/pnimcftx.html