Retrofit2.2说明-简单使用
很久前就想学习下Retrofit了,不过总是没有时间,正好最近新项目要用到网络请求,正好研究了下Retrofit2.2的简单使用方法,大致记录如下:
Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。网络请求依赖Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求了。
增加依赖:
compile 'com.squareup.retrofit2:retrofit:2.2.0'//Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.2.0'//ConverterFactory的Gson依赖包
这里需要值得注意的是导入的retrofit2包的版本必须要一致,否则就会报错。
这里我建立的请求地址 baseUrl 是 http://200.200.200.182:9999/
创建一个Retrofit对象:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://200.200.200.182:9999/")
//增加返回值为Gson的支持(以实体类返回)
.addConverterFactory(GsonConverterFactory.create())
.build();
接着只需要定义对应请求的接口,用来返回一个Call对象,下面举个栗子:
假设,我需要一个登录用户的操作,服务端给我的API请求地址是:
http://200.200.200.182:9999/login
请求协议是json格式,如:
{
"username" : "admin",
"password" : "123456"
}
@POST
这里先采用POST请求,使用注解@POST("login"),有如下两种方式:
方法一:
public interface RetrofitService
{
@FormUrlEncoded
@POST("login")
Call<ResponseBody> login(@Field("username") String username, @Field("password") String password);
}
方法二:
public interface RetrofitService
{
@Headers({"Content-type:application/json"})
@POST("login")
Call<ResponseBody> login(@Body User user);
}
//------------- User.java --------------------
/**
* Created by zyao89 on 2017/2/24.
*/
public class User
{
String username;
String password;
public User(String username, String password)
{
this.username = username;
this.password = password;
}
@Override
public String toString()
{
return "User{" +
"username='" + username + '/'' +
", password='" + password + '/'' +
'}';
}
}
接下来我们用之前的Retrofit对象创建一个mRetrofitService接口对象,也就是我们上面定义的那个RetrofitService接口,并且得到我们的Call对象,如下:
mRetrofitService = retrofit.create(RetrofitService.class);//这里采用的是Java的动态代理模式
接着用mRetrofitService调用我们上面定义的接口中方法,如:
public void login(View view)
{
// 方法一
Call<ResponseBody> login = mRetrofitService.login("admin", "123456");
// 方法二
// User user = new User("admin", "123456");
// Call<ResponseBody> login = mRetrofitService.login(user);
login.enqueue(getCallback());
}
利用得到的Call对象,然后我们就发出网络请求了,这里介绍下enqueue是异步操作,execute()为同步操作。
private Callback<ResponseBody> getCallback()
{
return new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{//请求成功
printLogCat("Code: " + response.code());
printLogCat("Message: " + response.message());
printLogCat("isSuccessful: " + response.isSuccessful());
try
{
printLogCat("Body: " + response.body().string());
}
catch (IOException e)
{
e.printStackTrace();
}
printLogCat("");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{//请求失败
printLogCat("ERROR: " + t.getMessage());
printLogCat("");
}
};
}
@GET
同样的协议,我们可以用GET请求来一遍,使用注解@ GET(""),有如下两种方式:
方式一:
public interface RetrofitService
{
@Headers({"Content-type:application/json"})
@GET("login")
Call<ResponseBody> login(@Query("username") String username, @Query("password") String password);
}
public void login(View view)
{
Call<ResponseBody> login = mRetrofitService.login("bacdd", "333444");
login.enqueue(getCallback());
}
请求URL:URL: /login?username=bacdd&password=333444
方法二:
public interface RetrofitService
{
@Headers({"Content-type:application/json"})
@GET("{url}")
Call<ResponseBody> login(@Path("url") String url, @Query("username") String username, @Query("password") String password);
}
@Path() 为占位符,可被参数动态替换;
public void login(View view)
{
Call<ResponseBody> login = mRetrofitService.login("login", "admin", "123444");
login.enqueue(getCallback());
}
请求URL:URL: /login?username= admin&password= 123444
@DELETE & @PUT
用法与前两者基本相同,这里就不阐述了;
参考代码如下:
@Headers({"Content-type:application/json"})
@PUT("put")
Call<ResponseBody> put(@Body User user);
@Headers({"Content-type:application/json"})
@HTTP(method = "DELETE", path = "/delete", hasBody = true)
Call<ResponseBody> delete(@Body DeleteID id);
备注下,Retrofit2.0以后,貌似DELETE请求是不可以带@Body参数的,所以,可改写成以上方式。
总结
@Path:所有在网址中的参数(URL的问号前面);
@Query:URL问号后面的参数;
@QueryMap:相当于多个@Query ;
@Field:用于POST请求,提交单个数据 ;(使用@Field时记得添加@FormUrlEncoded)
@Body:相当于多个@Field,以对象的形式提交
若需要重新定义接口地址,可以使用@Url,将地址以参数的形式传入即可。如:
@GET
Call<User> getUser(@Url String url);

Retrofit2.2说明-简单使用的更多相关文章
- 转载:Google 官方应用架构的最佳实践指南 赞👍
官方给的实践指南,很有实际的指导意义, 特别是对一些小公司,小团队,给了很好的参考意义. 原文地址: https://developer.android.com/topic/libraries/ar ...
- 基于RxJava2+Retrofit2简单易用的网络请求实现
代码地址如下:http://www.demodashi.com/demo/13473.html 简介 基于RxJava2+Retrofit2实现简单易用的网络请求,结合android平台特性的网络封装 ...
- Retrofit2.0起步篇
retrofit 英文名字是改装的意思,也就是说他是对网络请求的一种改装,他不负责进行网络请求,他是对请求方式的一种封装.真正进行网络请求的是okhttp. 以下所有内容在Android Studio ...
- android快捷开发之Retrofit网络加载框架的简单使用
大家都知道,安卓最大的特点就是开源化,这自然会产生很多十分好用的第三方API,而基本每一个APP都会与网络操作和缓存处理机制打交道,当然,你可以自己通过HttpUrlConnection再通过返回数据 ...
- Android 网络框架之Retrofit2使用详解及从源码中解析原理
就目前来说Retrofit2使用的已相当的广泛,那么我们先来了解下两个问题: 1 . 什么是Retrofit? Retrofit是针对于Android/Java的.基于okHttp的.一种轻量级且安全 ...
- 让你Android开发更简单
转载:http://www.jianshu.com/p/22ff8b5fdadc 搭建一个新的Android项目,你会怎么做? 每个人对应用框架的理解不相同,但是最终达到的效果应该是一样: ①降低项目 ...
- retrofit2中ssl的Trust anchor for certification path not found问题
在retrofit2中使用ssl,刚刚接触,很可能会出现如下错误. java.security.cert.CertPathValidatorException: Trust anchor for ce ...
- Android--Retrofit+RxJava的简单封装(三)
1,继续接着上一篇的讲讲,话说如果像上一篇这样的话,那么我们每一次请求一个结构都要创建一堆的Retrofit对象,而且代码都是相同的,我们可以试试封装一下 先创建一个HttpMethods类,将Ret ...
- Android--Retrofit的简单使用(一)
1,如果不太了解retrofit的同学可以先去官网学习一下简单使用:http://square.github.io/retrofit/,这里我们以一个简单的Get请求的例子来练习一下 2,https: ...
随机推荐
- cygwin开发环境搭建与apt-cyg的应用
1.Cygwin安装 http://www.cygwin.com/下载安装工具 详细安装过程參照http://jingyan.baidu.com/article/6b97984d83dfe51ca2b ...
- 也谈隐藏盘符等windows 的管理员的策略实现
网上的文章都知道在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer 文件夹下有控制隐藏驱动器 ...
- leetCode 30.Substring with Concatenation of All Words (words中全部子串相连) 解题思路和方法
Substring with Concatenation of All Words You are given a string, s, and a list of words, words, tha ...
- 转:NHibernate 存储过程
http://stackoverflow.com/questions/928847/how-to-get-the-return-value-from-a-sql-server-stored-proce ...
- View拖拽 自定义绑定view拖拽的工具类
由于工作需求,需要用到这种处理方法所以我就写了这个 废话不多说先看效果图 接下来就看代码吧 DragDropManager import android.app.Activity; import an ...
- android自定义View_2——Making the View Interactive
前言:绘制出一个view只是自定义view的一个部分,还需要自定义一些view的行为,来反馈用户的使用操作,反馈的 行为要合理性,就像真是的物理世界一样,不要太玄幻哦. 可以将view的行为封装到in ...
- SSH总结(一)
其实学习struts等框架,不仅要知道怎么用,我们还应该多去看看框架的源码,知道为什么可以这样使用,凡事都知道为什么,以这样的态度学习,我们才能更加深一步的理解原理好实现方式,本类博客主要是个人学习总 ...
- poj 3469(网络流模版)
题目链接:http://poj.org/problem?id=3469 思路:终于把网络流的模版测试好了,在Dinic和Sap之间还是选择了Sap,事实证明Sap确实比Dinic效率高,在此贴出自己的 ...
- NDK,在JNI层使用AssetManager读取文件
NDK,二进制文件数据读取,在JNI层,通过AAssetManager读取asset内部的资源: 需要头文件的支持 #include <android/asset_manager_jni.h&g ...
- 字符串匹配(KMP 算法 含代码)
主要是针对字符串的匹配算法进行解说 有关字符串的基本知识 传统的串匹配法 模式匹配的一种改进算法KMP算法 网上一比較易懂的解说 小样例 1计算next 2计算nextval 代码 有关字符串的基本知 ...