Retrofit 2.1 入门
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 入门的更多相关文章
- Retrofit网络框架入门使用
1.简单介绍 retrofit事实上就是对okhttp做了进一步一层封装优化. 我们仅仅须要通过简单的配置就能使用retrofit来进行网络请求了. Retrofit能够直接返回Bean对象,比如假设 ...
- Retrofit 入门学习
Retrofit 入门学习官方RetrofitAPI 官方的一个例子 public interface GitHubService { @GET("users/{user}/repos&qu ...
- Retrofit 从入门到了解【总结】
源码:https://github.com/baiqiantao/RetrofitDemo.git 参考:http://www.jianshu.com/p/308f3c54abdd Retrofit入 ...
- Retrofit学习入门
Retrofit的使用 设置权限与添加依赖 定义请求接口 通过创建一个retrofit生成一个接口的实现类(动态代理) 调用接口请求数据 设置权限与添加依赖 权限:首先确保在AndroidManife ...
- Retrofit入门
1 Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(ScalarsConverterFactory.create()) ...
- Retrofit 入门和提高
首先感谢这个哥们,把我从helloworld教会了. http://blog.csdn.net/angcyo/article/details/50351247 retrofit 我花了两天的时间才学会 ...
- MVP模式入门(结合Rxjava,Retrofit)
本文MVP的sample实现效果: github地址:https://github.com/xurui1995/MvpSample 老规矩,在说对MVP模式的理解之前还是要再谈谈MVC模式,了解了MV ...
- 「2020 新手必备 」极速入门 Retrofit + OkHttp 网络框架到实战,这一篇就够了!
老生常谈 什么是 Retrofit ? Retrofit 早已不是什么新技术了,想必看到这篇博客的大家都早已熟知,这里就不啰嗦了,简单介绍下: Retrofit 是一个针对 Java 和 Androi ...
- Android开发 retrofit入门讲解 (RxJava模式)
前言 retrofit除了正常使用以外,还支持RxJava的模式来使用,此篇博客讲解如何使用RxJava模式下的retrofit 依赖 implementation 'com.squareup.ret ...
随机推荐
- OpenXml入门---word里面插入图片
下面介绍如何在word里面插入图片,顺便小弟发现MSDN官网有完整的OpenXML教程,虽然是全英文的不过还是很有帮助的. Tips,原来摘抄代码里面没有模板,在copy过来发现插入word中的图片大 ...
- Codeforces 410C.Team[构造]
C. Team time limit per test 1 second memory limit per test 256 megabytes input standard input output ...
- 在ios android设备上使用 Protobuf (使用dll方式)
http://game.ceeger.com/forum/read.php?tid=13479 如果你的工程可以以.Net 2.0 subset模式运行,请看这个帖子中的方法. 地址:http://g ...
- u-boot移植初步尝试-tiny4412
获取u-boot源代码 在u-boot官方网站下载uboot源码.ftp://ftp.denx.de/pub/u-boot/ 因为是第一次移植uboot,所以这里选的版本是 u-boot-2013.0 ...
- [No000030]程序员节发点别的:中国教育整个把人脑子搞坏了-易中天
导读 在易中天看来,中国教育和中国文化的问题一样,是弱智化.搞坏的原因是什么?是我们的教育评价目标就是"成王败寇"四个字.他明确提出反对励志,反对培优,反对成功学,反对望子成龙.他 ...
- noip模拟赛(一)魔法树
魔法树 (mahou.pas/c/cpp) [问题描述] 魔法使moreD在研究一棵魔法树. 魔法树顾名思义,这货是一棵树,奇葩的是魔法树上的每一条边都拥有一个魔法属性,如果不那么奇葩就不是moreD ...
- luogu1097统计数字[noip2007提高组Day1T1]
题目描述 某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*10^9).已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出 ...
- 使用javascript对密码进行有密码强度提示的验证
好些网站的注册功能中,都有对密码进行验证并且还有强度提示.下面就来实现这种效果.密码强度说明:密码强度:弱——纯数字,纯字母,纯符号密码强度:中——数字,字母,符号任意两种的组合密码强度:强——数字, ...
- 关于codeMirror插件使用的一个坑
codeMirror插件可以做语法高亮渲染,但它操作过程是这样的:先从 textarea中读取值放到codemirror动态生成的div中,根据textarea中的换行个数确定行数,根据正则表达来高亮 ...
- 用django实现一个微信图灵机器人
微信的post请求格式是xml,所以django需要做的就是将xml请求解析出来,把content发送到图灵机器人接口, 接口返回的json数据把主要内容给解析出来,然后重新封装成xml返回给微信客户 ...