Retrofit 2.1入门

, map);
    try {
        Response<String>body=call.execute();
        System.out.print(body.body());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

query 访问的参数会添加到路径(path)的后面.

实际访问的url是 http://tieba.baidu.com/sheet?name=laiqurufeng&age=22&gender=male&address=sz  (模拟的访问)

encoded =true表示对url的query进行url编码,同理还有encodeValues. 这2个的值默认都是true的

如果上面的代码换成 map.put("性别","男") ,然后更改@QueryMap(encoded =false )

那么实际访问的url变成了 http://tieba.baidu.com/sheet?name=laiqurufeng&age=22&性别=%E7%94%B7&address=sz (可以看到key没有进行url编码,value进行了url编码).

Header注解

header分为key和value都固定,静态Header注解方法 和 动态Header注解方法

注意header不会相互覆盖.

静态Header

interface FixedHeader{

@Headers({    //静态Header

"Accept: application/vnd.github.v3.full+json",

"User-Agent: Retrofit-Sample-App"

})

@GET("/")

Call<ResponseBody> getResponse();

}

动态Header

interface DynamicHeader{

@Headers("Cache-Control: max-age=640000")       //动态Header

@GET("/")

Call<ResponseBody> getResponse(

@Header("header1")String header1,

@Header("header2")String header2);

//动态Header,其value值可以在调用这个方法时动态传入.

}

例子:

public class PhoneResult {
    /**
     * errNum : 0
     * retMsg : success
     * retData : {"phone":"15210011578","prefix":"1521001","supplier":"移动","province":"北京","city":"北京","suit":"152卡"}
     */
    public int errNum;
    public String retMsg;
    /**
     * phone : 15210011578
     * prefix : 1521001
     * supplier : 移动
     * province : 北京
     * city : 北京
     * suit : 152卡
     */
    public RetDataEntity retData;
    public static class RetDataEntity {
        public String phone;
        public String prefix;
        public String supplier;
        public String province;
        public String city;
        public String suit;

        @Override
        public String toString() {
            return "RetDataEntity{" +
                    "phone='" + phone + '\'' +
                    ", prefix='" + prefix + '\'' +
                    ", supplier='" + supplier + '\'' +
                    ", province='" + province + '\'' +
                    ", city='" + city + '\'' +
                    ", suit='" + suit + '\'' +
                    '}';
        }
    }
}

Service:

动态Header

public interface PhoneService {
    @GET("/apistore/mobilenumber/mobilenumber")
    Call<PhoneResult> getResult(
            @Header("apikey")String apikey,
            @Query("phone")String phone
    );
}

静态Header

public interface PhoneServiceDynamic {
    @Headers("apikey:8e13586b86e4b7f3758ba3bd6c9c9135")
    @GET("/apistore/mobilenumber/mobilenumber")
    Call<PhoneResult> getResult(
            @Query("phone")String phone
    );
}

调用

public static void phone_Query(String phone){
    final String BASE_URL="http://apis.baidu.com";
    final String API_KEY="8e13586b86e4b7f3758ba3bd6c9c9135";
    //1.创建Retrofit对象
    Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    //2.创建访问API的请求
    PhoneService service=retrofit.create(PhoneService.class);
    Call<PhoneResult>call=service.getResult(API_KEY,phone);
    //3.发送请求
    try {
        Response<PhoneResult>response=call.execute();
        //4.处理结果
        if (response.isSuccessful()) {
            PhoneResult result=response.body();
            if (result!=null) {
                PhoneResult.RetDataEntity entity = result.getRetData();
                System.out.print(entity.toString());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*异步调用

call.enqueue(new Callback<PhoneResult>() {
        @Override
        public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
            //4.处理结果
            if (response.isSuccessful()) {
                PhoneResult result=response.body();
                if (result!=null) {
                    PhoneResult.RetDataEntity entity = result.getRetData();
                    System.out.print(entity.toString());
                }
            }
        }
        @Override
        public void onFailure(Call<PhoneResult> call, Throwable t) {
        }
    });*/
}

上传文件

public interface UploadServer {
    @Headers({//静态Header
            "User-Agent: androidphone"
            })
    @Multipart
    @POST("/service.php?mod=avatar&type=big")
        // upload is a post field
        // without filename it didn't work! I use a constant name because server doesn't save file on original name
        //@Part("filename=\"1\" ") RequestBody
        //以表单的形式上传图片
    Call<JsonObject> uploadImageM(@Part("file\";filename=\"1") RequestBody file);
//    Call<ResponseBody> uploadImage(@Part("file\"; filename=\"image.png\"") RequestBody file);
    /**
     * 以二进制流的形式上传 图片
     * @param file
     * @return
     */
    @Headers({//静态Header
            "User-Agent:androidphone"
    })
    @POST("/service.php?mod=avatar&type=big")
    Call<ResponseBody> uploadImage(@Body RequestBody file);
}

调用

public static void upload(String fpath) { // path to file like /mnt/sdcard/myfile.txt
    String baseurl="http://dev.123go.net.cn";
    File file = new File(fpath);
    // please check you mime type, i'm uploading only images
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
    /*RequestBody rbody=new MultipartBody.Builder()
            .addPart(requestBody).build();
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("image/jpg"), file);
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("image", file.getName(), requestFile);
    */
    Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(baseurl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(getOkhttpClient())
            .build();
    // 添加描述
    /*String descriptionString = "hello, 这是文件描述";
    RequestBody description =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), descriptionString);*/
    UploadServer server=retrofit.create(UploadServer.class);
    Call<ResponseBody> call = server.uploadImage(requestBody);
    call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            ResponseBody jsonObject=response.body();
            System.out.print(jsonObject.toString());
        }
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
        }
    });
}

private static OkHttpClient getOkhttpClient(){
        final String cookie="your cookie";
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
//                                .addHeader("Content-Type", " application/x-www-form-urlencoded; charset=UTF-8")
//                                .addHeader("Accept-Encoding", "gzip, deflate")
//                                .addHeader("Connection", "keep-alive")
//                                .addHeader("Accept", "***")
                                .addHeader("Cookie", cookie)
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();

return httpClient;
    }

Retrofit 2.1 入门的更多相关文章

  1. Retrofit网络框架入门使用

    1.简单介绍 retrofit事实上就是对okhttp做了进一步一层封装优化. 我们仅仅须要通过简单的配置就能使用retrofit来进行网络请求了. Retrofit能够直接返回Bean对象,比如假设 ...

  2. Retrofit 入门学习

    Retrofit 入门学习官方RetrofitAPI 官方的一个例子 public interface GitHubService { @GET("users/{user}/repos&qu ...

  3. Retrofit 从入门到了解【总结】

    源码:https://github.com/baiqiantao/RetrofitDemo.git 参考:http://www.jianshu.com/p/308f3c54abdd Retrofit入 ...

  4. Retrofit学习入门

    Retrofit的使用 设置权限与添加依赖 定义请求接口 通过创建一个retrofit生成一个接口的实现类(动态代理) 调用接口请求数据 设置权限与添加依赖 权限:首先确保在AndroidManife ...

  5. Retrofit入门

    1 Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(ScalarsConverterFactory.create()) ...

  6. Retrofit 入门和提高

    首先感谢这个哥们,把我从helloworld教会了. http://blog.csdn.net/angcyo/article/details/50351247 retrofit 我花了两天的时间才学会 ...

  7. MVP模式入门(结合Rxjava,Retrofit)

    本文MVP的sample实现效果: github地址:https://github.com/xurui1995/MvpSample 老规矩,在说对MVP模式的理解之前还是要再谈谈MVC模式,了解了MV ...

  8. 「2020 新手必备 」极速入门 Retrofit + OkHttp 网络框架到实战,这一篇就够了!

    老生常谈 什么是 Retrofit ? Retrofit 早已不是什么新技术了,想必看到这篇博客的大家都早已熟知,这里就不啰嗦了,简单介绍下: Retrofit 是一个针对 Java 和 Androi ...

  9. Android开发 retrofit入门讲解 (RxJava模式)

    前言 retrofit除了正常使用以外,还支持RxJava的模式来使用,此篇博客讲解如何使用RxJava模式下的retrofit 依赖 implementation 'com.squareup.ret ...

随机推荐

  1. Semiautomated IMINT Processing Baseline System——翻译

    题目 半自动的IMINT(图像情报)处理基准系统 摘要 SAIP ACTD(半自动图像情报处理高级概念技术展示项目)的目的是,通过战略上的传感器采集,使图像成为指挥官掌控整个战场的主要源头.该采集系统 ...

  2. [c] base64

    / * Program: * base64 encode & decode * Author: * brant-ruan * Date: * 2016-02-29 * Usage: * Enc ...

  3. 【2016-10-15】【坚持学习】【Day6】【组合模式】

    哈哈,今天偷懒了,在晚上只看了一个组合模式. 例子: 树结构,有一些是树节点,一些是叶子节点. 比如,文件夹树结构,一个是文件夹节点,一个是文件节点,虽然都是树的节点,但是具体的业务肯定是区别的. 代 ...

  4. cookie与session的爱恨情仇

    这些都是基础知识,不过有必要做深入了解.先简单介绍一下. 二者的定义: 当你在浏览网站的时候,WEB 服务器会先送一小小资料放在你的计算机上,Cookie 会帮你在网站上所打的文字或是一些选择, 都纪 ...

  5. [No00001A]天天换图,百词斩到底在折腾啥

  6. Win7安装visual c++ 2015 redistributable x64失败

    from:http://www.fxyoke.cn/forum.php?mod=viewthread&tid=1171 在win7中安装visual c++ 2015 redistributa ...

  7. 分享一例测试环境下nginx+tomcat的视频业务部署记录

    需求说明:在测试环境下(192.168.1.28)部署一套公司某业务环境,其中:该业务前台访问地址: http://testhehe.wangshibo.com该业务后台访问地址: http://te ...

  8. js数组操作

    用 js有很久了,但都没有深究过js的数组形式.偶尔用用也就是简单的string.split(char).这段时间做的一个项目,用到数组的地方很多, 自以为js高手的自己居然无从下手,一下狠心,我学! ...

  9. 配置Tomcat使用Redis作为session管理

    1. 在 tomcat/lib 中增加以下jar包 commons-pool2-.jar jedis-.jar tomcat-redis-session-manager-.jar 2. 修改tomca ...

  10. react native中的欢迎页(解决首加载白屏)

    参照网页: http://blog.csdn.net/fengyuzhengfan/article/details/52712829 首先是在原生中写一些方法,然后通过react native中js去 ...