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. 准备使用 Office 365 中国版--安装

    温故而知新,先附上一个链接:Office 365常见问题 Office 365中Office套件的安装介质和传统Office套件的安装介质是有些区别的,虽然功能都一样.因此,如果购买了带Office套 ...

  2. [转]C#网络编程(基本概念和操作) - Part.1

    本文转自:http://www.tracefact.net/CSharp-Programming/Network-Programming-Part1.aspx 引言 C#网络编程系列文章计划简单地讲述 ...

  3. Machine Learning Algorithms Study Notes(3)--Learning Theory

    Machine Learning Algorithms Study Notes 高雪松 @雪松Cedro Microsoft MVP 本系列文章是Andrew Ng 在斯坦福的机器学习课程 CS 22 ...

  4. The Google Test and Development Environment (持续更新)

    最近Google Testing Blog上开始连载The Google Test and Development Environment(Google的测试和开发环境),因为blogspot被墙,我 ...

  5. NOIP2012借教室[线段树|离线 差分 二分答案]

    题目描述 在大学期间,经常需要租借教室.大到院系举办活动,小到学习小组自习讨论,都需要 向学校申请借教室.教室的大小功能不同,借教室人的身份不同,借教室的手续也不一样. 面对海量租借教室的信息,我们自 ...

  6. 自动化工作之自动更新SVN

    任务计划程序 任务计划程序是Window自带的组件 微软文档 http://windows.microsoft.com/zh-cn/windows-vista/automate-tasks-with- ...

  7. ubuntu下nginx+php5的部署

    ubuntu下nginx+php5环境的部署和centos系统下的部署稍有不同,废话不多说,以下为操作记录:1)nginx安装root@ubuntutest01-KVM:~# sudo apt-get ...

  8. Mysql备份系列(2)--mysqldump备份(全量+增量)方案操作记录

    在日常运维工作中,对mysql数据库的备份是万分重要的,以防在数据库表丢失或损坏情况出现,可以及时恢复数据. 线上数据库备份场景:每周日执行一次全量备份,然后每天下午1点执行MySQLdump增量备份 ...

  9. JS 关闭 页面 浏览器 事件

    JS监听关闭浏览器事件关键字: js监听关闭浏览器事件Onunload与OnbeforeunloadOnunload,onbeforeunload都是在刷新或关闭时调用,可以在<script&g ...

  10. ext 自带搜索功能