retrofit 简单使用

1. build.gradle

implementation'com.squareup.retrofit2:retrofit:2.9.0'

implementation'com.google.code.gson:gson:2.8.6'

implementation'com.squareup.retrofit2:converter-gson:2.9.0'

如果想使用最新版本,可以把版本号改为+,然后去 External Libraries,看看下载下来的lib的版本号,再把+改为 看到的版本号即可。。 为什么,再改回来,使用+,可能每次都去网络下载lib,导致编译很慢。

版本号固定,比如gson, 2.8.6,本地已经有了,直接使用本地,不会再网络请求。但是+号会,再次请求对比。不需要实时保持最新。

2. public interface GitHubService {

@GET("check_update.php")

Call>reqNewVersionApk();

}





3.

{

OkHttpClient.Builder builder =new OkHttpClient.Builder();

    if (Consts.isDebug) {

HttpLoggingInterceptor loggingInterceptor =new HttpLoggingInterceptor("Retrofit2");

        //log打印级别,决定了log显示的详细程度

        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);

        //log颜色级别,决定了log在控制台显示的颜色

        loggingInterceptor.setColorLevel(Level.INFO);

        builder.addInterceptor(loggingInterceptor);

    }

OkHttpClient client = builder.build();

    Retrofit retrofit =new Retrofit.Builder()

.client(client)

.baseUrl("http://www.xxx.xyz/xxx/app/")//要访问的主机地址,注意以 /(斜线) 结束,不然可能会抛出异常

            .addConverterFactory(GsonConverterFactory.create())//添加Gson

            .build();

    GitHubService service = retrofit.create(GitHubService.class);

    // xxx/app/

    Call> call = service.reqNewVersionApk();

    call.enqueue(new Callback>() {

@Override

        public void onResponse(Call> call, retrofit2.Response> response) {

RespBase appUpdateResp = response.body();

            MyLog.print("appUpdateResp.getCode:" + appUpdateResp.getCode());

            MyLog.print("appUpdateResp.getdata.apkurl:" + appUpdateResp.getData().getApkUrl());

        }

@Override

        public void onFailure(Call> call, Throwable t) {

MyLog.printError(t);

        }

});

}


4.HttpLoggingInterceptor

/*

* Copyright 2016 jeasonlzy(廖子尧)

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

*      http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package com.lzy.okgo.interceptor;

import com.lzy.okgo.utils.IOUtils;

import com.lzy.okgo.utils.OkLogger;

import java.io.IOException;

import java.nio.charset.Charset;

import java.util.concurrent.TimeUnit;

import java.util.logging.Logger;

import okhttp3.Connection;

import okhttp3.Headers;

import okhttp3.Interceptor;

import okhttp3.MediaType;

import okhttp3.Protocol;

import okhttp3.Request;

import okhttp3.RequestBody;

import okhttp3.Response;

import okhttp3.ResponseBody;

import okhttp3.internal.http.HttpHeaders;

import okio.Buffer;

/**

* ================================================

* 作    者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy

* 版    本:1.0

* 创建日期:2016/1/12

* 描    述:OkHttp拦截器,主要用于打印日志

* 修订历史:

* ================================================

*/

public class HttpLoggingInterceptorimplements Interceptor {

private static final CharsetUTF8 = Charset.forName("UTF-8");

    private volatile LevelprintLevel = Level.NONE;

    private java.util.logging.LevelcolorLevel;

    private Loggerlogger;

    public enum Level {

NONE,      //不打印log

        BASIC,      //只打印 请求首行 和 响应首行

        HEADERS,    //打印请求和响应的所有 Header

        BODY        //所有数据全部打印

    }

public HttpLoggingInterceptor(String tag) {

logger = Logger.getLogger(tag);

    }

public void setPrintLevel(Level level) {

if (printLevel ==null)throw new NullPointerException("printLevel == null. Use Level.NONE instead.");

        printLevel = level;

    }

public void setColorLevel(java.util.logging.Level level) {

colorLevel = level;

    }

private void log(String message) {

logger.log(colorLevel, message);

    }

@Override

    public Responseintercept(Chain chain)throws IOException {

Request request = chain.request();

        if (printLevel == Level.NONE) {

return chain.proceed(request);

        }

//请求日志拦截

        logForRequest(request, chain.connection());

        //执行请求,计算请求时间

        long startNs = System.nanoTime();

        Response response;

        try {

response = chain.proceed(request);

        }catch (Exception e) {

log("<-- HTTP FAILED: " + e);

            throw e;

        }

long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        //响应日志拦截

        return logForResponse(response, tookMs);

    }

private void logForRequest(Request request, Connection connection)throws IOException {

boolean logBody = (printLevel == Level.BODY);

        boolean logHeaders = (printLevel == Level.BODY ||printLevel == Level.HEADERS);

        RequestBody requestBody = request.body();

        boolean hasRequestBody = requestBody !=null;

        Protocol protocol = connection !=null ? connection.protocol() : Protocol.HTTP_1_1;

        try {

String requestStartMessage ="--> " + request.method() +' ' + request.url() +' ' + protocol;

            log(requestStartMessage);

            if (logHeaders) {

if (hasRequestBody) {

// Request body headers are only present when installed as a network interceptor. Force

// them to be included (when available) so there values are known.

                    if (requestBody.contentType() !=null) {

log("\tContent-Type: " + requestBody.contentType());

                    }

if (requestBody.contentLength() != -1) {

log("\tContent-Length: " + requestBody.contentLength());

                    }

}

Headers headers = request.headers();

                for (int i =0, count = headers.size(); i < count; i++) {

String name = headers.name(i);

                    // Skip headers from the request body as they are explicitly logged above.

                    if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {

log("\t" + name +": " + headers.value(i));

                    }

}

log(" ");

                if (logBody && hasRequestBody) {

if (isPlaintext(requestBody.contentType())) {

bodyToString(request);

                    }else {

log("\tbody: maybe [binary body], omitted!");

                    }

}

}

}catch (Exception e) {

OkLogger.printStackTrace(e);

        }finally {

log("--> END " + request.method());

        }

}

private ResponselogForResponse(Response response, long tookMs) {

Response.Builder builder = response.newBuilder();

        Response clone = builder.build();

        ResponseBody responseBody = clone.body();

        boolean logBody = (printLevel == Level.BODY);

        boolean logHeaders = (printLevel == Level.BODY ||printLevel == Level.HEADERS);

        try {

log("<-- " + clone.code() +' ' + clone.message() +' ' + clone.request().url() +" (" + tookMs +"ms)");

            if (logHeaders) {

Headers headers = clone.headers();

                for (int i =0, count = headers.size(); i < count; i++) {

log("\t" + headers.name(i) +": " + headers.value(i));

                }

log(" ");

                if (logBody && HttpHeaders.hasBody(clone)) {

if (responseBody ==null)return response;

                    if (isPlaintext(responseBody.contentType())) {

byte[] bytes = IOUtils.toByteArray(responseBody.byteStream());

                        MediaType contentType = responseBody.contentType();

                        String body =new String(bytes, getCharset(contentType));

                        log("\tbody:" + body);

                        responseBody = ResponseBody.create(responseBody.contentType(), bytes);

                        return response.newBuilder().body(responseBody).build();

                    }else {

log("\tbody: maybe [binary body], omitted!");

                    }

}

}

}catch (Exception e) {

OkLogger.printStackTrace(e);

        }finally {

log("<-- END HTTP");

        }

return response;

    }

private static CharsetgetCharset(MediaType contentType) {

Charset charset = contentType !=null ? contentType.charset(UTF8) :UTF8;

        if (charset ==null) charset =UTF8;

        return charset;

    }

/**

* Returns true if the body in question probably contains human readable text. Uses a small sample

* of code points to detect unicode control characters commonly used in binary file signatures.

*/

    private static boolean isPlaintext(MediaType mediaType) {

if (mediaType ==null)return false;

        if (mediaType.type() !=null && mediaType.type().equals("text")) {

return true;

        }

String subtype = mediaType.subtype();

        if (subtype !=null) {

subtype = subtype.toLowerCase();

            if (subtype.contains("x-www-form-urlencoded") || subtype.contains("json") || subtype.contains("xml") || subtype.contains("html"))//

                return true;

        }

return false;

    }

private void bodyToString(Request request) {

try {

Request copy = request.newBuilder().build();

            RequestBody body = copy.body();

            if (body ==null)return;

            Buffer buffer =new Buffer();

            body.writeTo(buffer);

            Charset charset =getCharset(body.contentType());

            log("\tbody:" + buffer.readString(charset));

        }catch (Exception e) {

OkLogger.printStackTrace(e);

        }

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354