简介:
Retrofit与Okhttp共同出自于Square公司,retrofit就是对Okhttp做了一层封装。把网络请求都交给给了Okhttp,我们只需要通过简单的配置就能使用Retrofit来进行网络请求了。下面是关于Retrofit学习的一个小Demo:<get请求>
1. 导包:
implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0' implementation 'com.android.support:design:27.1.1' implementation 'com.github.bumptech.glide:glide:4.7.1'
2. 定义我们的api:(在这感谢gank.io)
http://gank.io/api/data/福利/50/1
2. 代码:
1>定义接口GankApiService
import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; /** * @author jkloshhm 2018-05-16 */ public interface GankApiService { /** * 根据category获取Android、iOS等干货数据 * * @param category 类别 * @param count 条目数目 * @param page 页数 * @return Call<GankFuliDataResponse> */ @GET("data/{category}/{count}/{page}") Call<GankFuliDataResponse> getCategoryData(@Path("category") String category, @Path("count") int count, @Path("page") int page); }2>新建请求实体类GankFuliDataResponse .java:
package com.example.jkloshhm.retrofitdemo; import java.util.List; /** * @author jkloshhm 2018-05-16 */ public class GankFuliDataResponse { /** * error : false * results : [{"_id":"591a4a02421aa92c794632c8","createdAt":"2017-05-16T08:38:26.35Z","desc":"5-16", * "publishedAt":"2017-05-16T12:10:38.580Z","source":"chrome","type":"福利", * "url":"http://ww1.sinaimg.cn/large/610dc034ly1ffmwnrkv1hj20ku0q1wfu.jpg", * "used":true,"who":"daimajai"},{"_id":"59187082421aa91c8da340d1","createdAt": * "2017-05-14T22:58:10.836Z","desc":"5-14","publishedAt":"2017-05-15T12:03:44.165Z","source": * "chrome","type":"福利","url":"https://ws1.sinaimg.cn/large/610dc034ly1ffla9ostxuj20ku0q2abt.jpg", * "used":true,"who":"带马甲"},{"_id":"59154ae7421aa90c7a8b2b0d","createdAt":"2017-05-12T13:40:55.505Z", * "desc":"5-13","publishedAt":"2017-05-12T13:44:54.673Z","source":"chrome","type":"福利", * "url":"http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-12-18380140_455327614813449_854681840315793408_n.jpg", * "used":true,"who":"daimajia"},{"_id":"5913d09d421aa90c7fefdd8e","createdAt":"2017-05-11T10:46:53.608Z", * "desc":"5-11","publishedAt":"2017-05-11T12:03:09.581Z","source":"chrome","type":"福利", * "url":"http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-11-18380166_305443499890139_8426655762360565760_n.jpg", * "used":true,"who":"代码家"},{"_id":"591264ce421aa90c7a8b2aec","createdAt":"2017-05-10T08:54:38.531Z", * "desc":"5-10","publishedAt":"2017-05-10T11:56:10.18Z","source":"chrome","type":"福利", * "url":"http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-10-18382517_1955528334668679_3605707761767153664_n.jpg","used":true,"who":"带马甲"}] */ private boolean error; private List<ResultsBean> results; public boolean isError() { return error; } public void setError(boolean error) { this.error = error; } public List<ResultsBean> getResults() { return results; } public void setResults(List<ResultsBean> results) { this.results = results; } public static class ResultsBean { /** * _id : 591a4a02421aa92c794632c8 * createdAt : 2017-05-16T08:38:26.35Z * desc : 5-16 * publishedAt : 2017-05-16T12:10:38.580Z * source : chrome * type : 福利 * url : http://ww1.sinaimg.cn/large/610dc034ly1ffmwnrkv1hj20ku0q1wfu.jpg * used : true * who : daimajai */ private String _id; private String createdAt; private String desc; private String publishedAt; private String source; private String type; private String url; private boolean used; private String who; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getPublishedAt() { return publishedAt; } public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public boolean isUsed() { return used; } public void setUsed(boolean used) { this.used = used; } public String getWho() { return who; } public void setWho(String who) { this.who = who; } } }
3>主MainActivity.java
package com.example.jkloshhm.retrofitdemo;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.List;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author jkloshhm 2018-05-16
*/
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fabButton;
private ImageView imageView;
private List<GankFuliDataResponse.ResultsBean> resultsBeanList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fabButton = findViewById(R.id.fab);
imageView = findViewById(R.id.image);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://gank.io/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GankApiService gankApiService = retrofit.create(GankApiService.class);
//50代表有50条数据
Call<GankFuliDataResponse> gankFuliDataResponse = gankApiService.getCategoryData("福利", 50, 1);
gankFuliDataResponse.enqueue(new Callback<GankFuliDataResponse>() {
@Override
public void onResponse(@Nullable Call<GankFuliDataResponse> call,
@Nullable final Response<GankFuliDataResponse> response) {
resultsBeanList = response.body().getResults();
if (resultsBeanList != null) {
String imgageurl = resultsBeanList.get(0).getUrl();
Glide.with(MainActivity.this).load(imgageurl).into(imageView);
//点击按钮显示50张图片中随机的一张
fabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
int i = random.nextInt(50);
Log.i("jkl", "随机数" + i);
String imgageurl = resultsBeanList.get(i).getUrl();
Glide.with(MainActivity.this)
.load(imgageurl)
.into(imageView);
}
});
}
}
@Override
public void onFailure(Call<GankFuliDataResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "获取图片失败", Toast.LENGTH_SHORT).show();
}
});
}
}
4>activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:src="@mipmap/ic_launcher" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="16dp" android:clickable="true" app:borderWidth="1dp" app:elevation="3dp" app:pressedTranslationZ="6dp" app:rippleColor="#ffffff" /> </FrameLayout>
5>Mainfest里面加上Intent权限
<uses-permission android:name="android.permission.INTERNET"/>