http://blog.csdn.net/baidu_31093133/article/details/51759452 (transfer)
1. What is the Retrofit framework?
It is a very popular network framework developed by Square, so we can see the company's name when importing its package. The current version is 2.
Features:
Good performance, fast processing, easy to use, Retrofit is one of the most popular HTTP Client libraries on Android. It
uses REST API design style
to support NIO (new i/o)
and uses OKHttp to process network requests by default. I think it can be regarded as an enhancement of OKHttp .
Use Gson parsing by default
Into the title.
===================================
2. How to use it?
step:
1. Guide package
After compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' is
synchronized, it will be added in External Libraries:
retrofit-2.0.0-beta4
okhttp-3.0.1
okio-1.6.0
compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’
After synchronization, it will be added in External Libraries:
retrofit-2.0.0-beta4
okhttp-3.0.1
okio-1.6.0
gson-2.4
converter-gson-2.0.0-beta4
These packages are developed by Squareup.
So we can just compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'.
2. Understand the common annotation interfaces for network access in Retrofit2. In fact, these interfaces are under the retrofit2.http package.
1. @GET GET network request method
2, @POST POST network request method
3, @Headers() header information parameter
4, @Path() path parameter, replace the part enclosed by { } in the url address
5, @Query() For query parameters, a string similar to "page = 1" will be appended to the url address to form the request parameters submitted to the server
. 7.
@FormUrlEncoded
encodes the content filled in the form field to avoid garbled characters. 8. @Field
() specifies the name and corresponding value of each space in the form field.
9. @FieldMap form field collection
10. @Multipart Post submits a block request, if uploading a file, you must specify Multipart
11, @Body Post to submit a block request
3. Code steps:
1、定义一个接口(封装URL地址和数据请求)
2、实例化Retrofit
3、通过Retrofit实例创建接口服务对象
4、接口服务对象调用接口中方法,获得Call对象
5、Call对象执行请求(异步、同步请求)
测试Url:
https://api.github.com/users/basil2style
其中https://api.github.com/users/是BASE_URL,也就是基础地址,basil2style是GET的参数,如果访问成功会返回给我们一个json字符串:
{
"login": "basil2style",
"id": 1285344,
"avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/basil2style",
"html_url": "https://github.com/basil2style",
"followers_url": "https://api.github.com/users/basil2style/followers",
"following_url": "https://api.github.com/users/basil2style/following{/other_user}",
"gists_url": "https://api.github.com/users/basil2style/gists{/gist_id}",
"starred_url": "https://api.github.com/users/basil2style/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/basil2style/subscriptions",
"organizations_url": "https://api.github.com/users/basil2style/orgs",
"repos_url": "https://api.github.com/users/basil2style/repos",
"events_url": "https://api.github.com/users/basil2style/events{/privacy}",
"received_events_url": "https://api.github.com/users/basil2style/received_events",
"type": "User",
"site_admin": false,
"name": "Basil",
"company": "MakeInfo",
"blog": "http://www.themakeinfo.com",
"location": "Peterborough,ON,Canada",
"email": "[email protected]",
"hireable": true,
"bio": null,
"public_repos": 45,
"public_gists": 4,
"followers": 52,
"following": 145,
"created_at": "2011-12-26T00:17:22Z",
"updated_at": "2016-06-23T20:22:05Z"
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
好,按步骤开始写代码
1、定义一个接口(封装URL地址和数据请求)
RequestServices.java
package com.example.eventbus.retrofittest;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by LHD on 2016/6/25.
*/
public interface RequestServices {
//请求方式为GET,参数为basil2style,因为没有变量所以下面getString方法也不需要参数
@GET("basil2style")
//定义返回的方法,返回的响应体使用了ResponseBody
Call<ResponseBody> getString();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
我们通常把基础地址都放在一个类里,方便调用
Constant.java
package com.example.eventbus.retrofittest;
/**
* Created by LHD on 2016/6/25.
*/
public class Constant {
//baseurl
public final static String URL_BASE = "https://api.github.com/users/";
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
2、实例化Retrofit
//获取Retrofit对象,设置地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL_BASE)
.build();
- 1
- 2
- 3
- 4
3、通过Retrofit实例创建接口服务对象
RequestServices requestServices = retrofit.create(RequestServices.class);
- 1
4、接口服务对象调用接口中方法,获得Call对象
Call<ResponseBody> call = requestServices.getString();
- 1
5、Call对象执行请求(异步、同步请求)
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()){
try {
Log.i("LHD",response.body().toString());
//返回的结果保存在response.body()中
String result = response.body().string();
//onResponse方法是运行在主线程也就是UI线程的,所以我们可以在这里
//直接更新UI
textView.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("LHD","访问失败");
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
全部代码:
MainActivity.java
package com.example.eventbus.retrofittest;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private Context mContext = this;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initRetrofit();
}
private void initView(){
textView = (TextView) findViewById(R.id.tv_retrofit);
}
private void initRetrofit(){
//获取Retrofit对象,设置地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL_BASE)
.build();
Log.i("LHD","1");
RequestServices requestServices = retrofit.create(RequestServices.class);
Call<ResponseBody> call = requestServices.getString();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()){
try {
Log.i("LHD",response.body().toString());
//返回的结果保存在response.body()中
String result = response.body().string();
//onResponse方法是运行在主线程也就是UI线程的,所以我们可以在这里
//直接更新UI
textView.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("LHD","访问失败");
}
});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
我们的代码就是将请求的返回值显示在一个textview上,最后的效果如图所示:
Retrofit2中GET请求的写法
1、GET请求,方法中无参数
@GET(“article/page=1”)//并不是全部的Url地址,这个地址会和BaseUrl一起组成一个新的地址。组合的时候要小心。
Call<ResponseBody> getString(); //这个方法名字是自定义的,因为基本地址里没有变量,所以我们的自定义方法里也没有参数,其实这个方法的参数就是要添加到这个地址里的参数。
//ResponseBody是响应体
- 1
- 2
- 3
2、GET请求,方法中指定@Path参数和@Query参数
@Path用于替换url地址中{和}所括的部分。
@Query将在url地址中追加类似“page=1”的字符串,形成提交给服务端的请求参数
@GET(article/list/{type}?)
Call<QiushiModel>getList(
@Path('type')String type,
@Query('page')int page
);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
3、GET请求,提交表单数据。方法中定义@QueryMap参数。
@QueryMap参数将在url地址中追加类似 “type=text&count=30&page=1”的字符串。
@GET("MyWeb/RegServlet")
Call<ResponseBody>getKey(@QueryMap Map<String,String>map);
- 1
- 2
- 3
4、GET请求,方法中无参数。但在@Url里定义完整URL路径,这种情况下BaseUrl会被忽略。
@GET("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2299165671,2554860548&fm=116&gp=0.jpg");
Call<ResponsBody>getData();
- 1
- 2
这就是最简单的retrofit网络访问的过程啦。下一篇会更深入的讲解,POST请求,获取网络图片,使用Gson解析返回的json文件等等。