android之OkHttpClient通信「建议收藏」

android之OkHttpClient通信OkHttpClient用法1:自定义缓存OkHttpClienthttpclient=newOkHttpClient.Builder().cache(newCache(newFile("cacheDirectory"),newLong(10*1024*1024))).build();用法2:当…

大家好,又见面了,我是你们的朋友全栈君。

android之OkHttpClient通信


OkHttpClient

用法1:自定义缓存

OkHttpClient httpclient = new OkHttpClient.Builder()
        .cache(new Cache(new File("cacheDirectory"), new Long(10 * 1024 * 1024)))
        .build();

用法2:当出现缓存冲突时(常用)

OkHttpClient httpclient = new OkHttpClient();

提交请求:

用法1:
httpclient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

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

    }
});

用法2:

Response response = httpclient.newCall(request).execute();




Request类
Request request = new Request.Builder()        .url("www.baidu.com")        .header("User-Agent", "OkHttp Header1.java")//键值对,唯一        .header("User-Agent", "OkHttp Header2.java")//再次使用相同字段,值被覆盖        .addHeader("Accept", "application/json; q=0.5")//添加不覆盖,这时又两个“key”,值分别为"value2"、"value3"        .addHeader("Accept", "application/vnd.github.v3+json")//add几个就增加几个        .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "postBody"))        //RequestBody内容可以很丰富,第二个参数可以是多种类型的字符集        .build();




RequestBody

需要MediaType

用法1:
RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),body);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
MediaType mediaType = MediaType.parse("image/png");



用法2:

RequestBody requestBody = new RequestBody() {
    @Override public MediaType contentType() {
        return MediaType.parse("text/x-markdown; charset=utf-8");;
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
        sink.writeUtf8("Numbers\n");
        sink.writeUtf8("-------\n");
        for (int i = 2; i <= 997; i++) {
            sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
        }
    }

    private String factor(int n) {
        for (int i = 2; i < n; i++) {
            int x = n / i;
            if (x * i == n) return factor(x) + " × " + i;
        }
        return Integer.toString(n);
    }
};

用法3:

RequestBody formBody = new FormBody.Builder()
        .add("search", "Jurassic Park")
        .addEncoded("encoded","utf-8")
        .build();

用法4:

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addPart(Header,RequestBody)//添加包含头和body的Part
        .addFormDataPart("title", "Square Logo")//表单中添加表单
        .addFormDataPart("image", "logo-square.png",
                RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();




MediaType

配置请求类型

MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
MediaType mediaType = MediaType.parse("image/png");




Response

用法1:

Response response = httpclient.newCall(request).execute();

用法2:

httpclient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        
    }

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

    }
});
ResponseBody responseBody = response.body();
response.body().string();
response.code();//HTTP status code
response.header("key1");
response.header("key2");
response.headers("key1");
response.networkResponse();

还有很多实用的方法。



GitHub:链接
点击打开链接

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/126999.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(1)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号