今天就跟大家聊聊有关如何在Android中利用Retrofit与Rxjava实现网络请求,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。首先做一下准备工作,导入需要引用的文件compi
今天就跟大家聊聊有关如何在Android中利用Retrofit与Rxjava实现网络请求,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
首先做一下准备工作,导入需要引用的文件
compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' compile 'io.Reactivex:rxjava:1.1.0' compile 'io.reactivex:rxandroid:1.1.0' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' compile 'com.Google.code.gson:gson:2.6.2' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.android.support:recyclerview-v7:25.1.0'
网络请求的地址:https://api.douban.com/v2/movie/top250?start=0&count=10
添加网络请求权限
<uses-permission android:name="android.permission.INTERNET"/>
首先看一下Retrofit的使用基本用法
创建一个接口类MovieService 对网络接口进行请求这里写代码片
构建网络请求
public interface MovieService { @GET("top250") Call<MovieBean> getTopMovie(@Query("start")int start, @Query("count")int count);}
String baseUrl="Https://api.douban.com/v2/movie/"; Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); MovieService service = retrofit.create(MovieService.class); service.getTopMovie(0,10) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<MovieBean>() { @Override public void onCompleted() { Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { resultTV.setText(e.getMessage()); } @Override public void onNext(MovieBean movieBean) { resultTV.setText(movieBean.getTitle()); } }); Call<MovieBean> call = service.getTopMovie(0, 10); call.enqueue(new Callback<MovieBean>() { @Override public void onResponse(Call<MovieBean> call, Response<MovieBean> response) { MovieBean body = response.body(); resultTV.setText(response.body().getTitle()); System.out.println("成功"+response.body().getCount()); } @Override public void onFailure(Call<MovieBean> call, Throwable t) { resultTV.setText(t.getMessage()); } });
现在看看我们的布局文件MainActivity的xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="ledon.com.retrofitdemo.MainActivity"> <Button android:id="@+id/click_me_BN" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:padding="5dp" android:text="获取数据" android:textSize="16sp"/> <ListView android:id="@+id/result_TV" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/click_me_BN" android:textSize="16sp"/></RelativeLayout>
接下来就看看怎么样和RxJava的完美结合了。
首先改造一下MovieService这个接口
public interface MovieService { @GET("top250") Observable<MovieBean> getTopMovie(@Query("start")int start, @Query("count")int count);}
然后看一下我们需要创建一个HttpMethods关于一个http的请求方法
package ledon.com.retrofitdemo.api;import java.util.List;import java.util.concurrent.TimeUnit;import javax.security.auth.Subject;import ledon.com.retrofitdemo.MovieBean;import okhttp3.OkHttpClient;import retrofit2.Retrofit;import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;import retrofit2.converter.gson.GsonConverterFactory;import rx.Subscriber;import rx.android.schedulers.AndroidSchedulers;import rx.functions.Func1;import rx.schedulers.Schedulers;public class HttpMethods { public static final String BASE_URL="https://api.douban.com/v2/movie/"; private static final int DEFAULT_TIMEOUT=5; private Retrofit retrofit; private MovieService movieService; //私有化构造方法 private HttpMethods(){ //手动创建一个okhttpClient并设置超时时间 OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); retrofit=new Retrofit.Builder() .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(BASE_URL) .build(); movieService = retrofit.create(MovieService.class); } //在访问httpmethods时候创建单例 private static class SingletonHolder{ private static final HttpMethods INSTANCE=new HttpMethods(); } //获取单例 public static HttpMethods getInstance(){ return SingletonHolder.INSTANCE; } public void getTopMovie(Subscriber<MovieBean>subscriber, int start, int count){ movieService.getTopMovie(start, count) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); }}
so,很简单,我们的结合之路已经完成,另附源代码
package ledon.com.retrofitdemo;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.widget.Button;import android.widget.ListView;import android.widget.RelativeLayout;import android.widget.Toast;import java.util.List;import butterknife.Bind;import butterknife.ButterKnife;import butterknife.OnClick;import ledon.com.retrofitdemo.adapter.MovieAdapter;import ledon.com.retrofitdemo.api.HttpMethods;import rx.Subscriber;public class MainActivity extends AppCompatActivity { @Bind(R.id.click_me_BN) Button clickMeBN; @Bind(R.id.result_TV) ListView resultTV; @Bind(R.id.activity_main) RelativeLayout activityMain; private Subscriber<MovieBean> subscriber; private List<MovieBean.SubjectsBean> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); //resultTV.setAdapter(); } //进行网络请求 private void getMovie() { subscriber = new Subscriber<MovieBean>() { @Override public void onCompleted() { Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { //resultTV.setText(e.getMessage()); } @Override public void onNext(MovieBean movieBean) { // List<MovieBean.SubjectsBean> subjects = movieBean.getSubjects(); list=movieBean.getSubjects(); MovieAdapter movieAdapter=new MovieAdapter(MainActivity.this,list); resultTV.setAdapter(movieAdapter); //resultTV.setText(movieBean.getTitle()); } }; HttpMethods.getInstance().getTopMovie(subscriber, 0, 10); //Call<MovieBean> call = service.getTopMovie(0, 10); } @OnClick(R.id.click_me_BN) public void onClick() { getMovie(); }}
package ledon.com.retrofitdemo;import java.util.List;public class MovieBean { private int count; private int start; private int total; private String title; private List<SubjectsBean> subjects; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<SubjectsBean> getSubjects() { return subjects; } public void setSubjects(List<SubjectsBean> subjects) { this.subjects = subjects; } public static class SubjectsBean { private RatingBean rating; private String title; private int collect_count; private String original_title; private String subtype; private String year; private ImagesBean images; private String alt; private String id; private List<String> genres; private List<CastsBean> casts; private List<DirectorsBean> directors; public RatingBean getRating() { return rating; } public void setRating(RatingBean rating) { this.rating = rating; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getCollect_count() { return collect_count; } public void setCollect_count(int collect_count) { this.collect_count = collect_count; } public String getOriginal_title() { return original_title; } public void setOriginal_title(String original_title) { this.original_title = original_title; } public String getSubtype() { return subtype; } public void setSubtype(String subtype) { this.subtype = subtype; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public ImagesBean getImages() { return images; } public void setImages(ImagesBean images) { this.images = images; } public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getGenres() { return genres; } public void setGenres(List<String> genres) { this.genres = genres; } public List<CastsBean> getCasts() { return casts; } public void setCasts(List<CastsBean> casts) { this.casts = casts; } public List<DirectorsBean> getDirectors() { return directors; } public void setDirectors(List<DirectorsBean> directors) { this.directors = directors; } public static class RatingBean { private int max; private double average; private String stars; private int min; public int getMax() { return max; } public void setMax(int max) { this.max = max; } public double getAverage() { return average; } public void setAverage(double average) { this.average = average; } public String getStars() { return stars; } public void setStars(String stars) { this.stars = stars; } public int getMin() { return min; } public void setMin(int min) { this.min = min; } } public static class ImagesBean { private String small; private String large; private String medium; public String getSmall() { return small; } public void setSmall(String small) { this.small = small; } public String getLarge() { return large; } public void setLarge(String large) { this.large = large; } public String getMedium() { return medium; } public void setMedium(String medium) { this.medium = medium; } } public static class CastsBean { private String alt; private AvatarsBean avatars; private String name; private String id; public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public AvatarsBean getAvatars() { return avatars; } public void setAvatars(AvatarsBean avatars) { this.avatars = avatars; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public static class AvatarsBean { private String small; private String large; private String medium; public String getSmall() { return small; } public void setSmall(String small) { this.small = small; } public String getLarge() { return large; } public void setLarge(String large) { this.large = large; } public String getMedium() { return medium; } public void setMedium(String medium) { this.medium = medium; } } } public static class DirectorsBean { private String alt; private AvatarsBeanX avatars; private String name; private String id; public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public AvatarsBeanX getAvatars() { return avatars; } public void setAvatars(AvatarsBeanX avatars) { this.avatars = avatars; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public static class AvatarsBeanX { private String small; private String large; private String medium; public String getSmall() { return small; } public void setSmall(String small) { this.small = small; } public String getLarge() { return large; } public void setLarge(String large) { this.large = large; } public String getMedium() { return medium; } public void setMedium(String medium) { this.medium = medium; } } } }}
package ledon.com.retrofitdemo.adapter;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import java.util.List;import ledon.com.retrofitdemo.MovieBean;import ledon.com.retrofitdemo.R;public class MovieAdapter extends BaseAdapter { private Context context; private List<MovieBean.SubjectsBean> lists; public MovieAdapter(Context context, List<MovieBean.SubjectsBean> lists) { this.context = context; this.lists = lists; } @Override public int getCount() { System.out.println("集合大小:"+lists.size()); return lists.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View convertView, ViewGroup viewGroup) { ViewHolder holder; if (convertView==null){ convertView = LayoutInflater.from(context).inflate(R.layout.item, null); holder=new ViewHolder(); holder.tv_title= (TextView) convertView.findViewById(R.id.tv_title); holder.tv_name= (TextView) convertView.findViewById(R.id.tv_name); convertView.setTag(holder); }else { holder= (ViewHolder) convertView.getTag(); } //MovieBean.SubjectsBean subjectsBean = lists.get(i).getSubjects().get(i); holder.tv_title.setText(lists.get(i).getTitle());// holder.tv_name.setText(lists.get(i).getCasts().get(i).getName()); return convertView; } static class ViewHolder{ TextView tv_title; TextView tv_name; }}
package ledon.com.retrofitdemo.api;import java.util.List;import java.util.concurrent.TimeUnit;import javax.security.auth.Subject;import ledon.com.retrofitdemo.MovieBean;import okhttp3.OkHttpClient;import retrofit2.Retrofit;import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;import retrofit2.converter.gson.GsonConverterFactory;import rx.Subscriber;import rx.android.schedulers.AndroidSchedulers;import rx.functions.Func1;import rx.schedulers.Schedulers;public class HttpMethods { public static final String BASE_URL="https://api.douban.com/v2/movie/"; private static final int DEFAULT_TIMEOUT=5; private Retrofit retrofit; private MovieService movieService; //私有化构造方法 private HttpMethods(){ //手动创建一个okhttpClient并设置超时时间 OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); retrofit=new Retrofit.Builder() .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(BASE_URL) .build(); movieService = retrofit.create(MovieService.class); } //在访问httpmethods时候创建单例 private static class SingletonHolder{ private static final HttpMethods INSTANCE=new HttpMethods(); } //获取单例 public static HttpMethods getInstance(){ return SingletonHolder.INSTANCE; } public void getTopMovie(Subscriber<MovieBean>subscriber, int start, int count){ movieService.getTopMovie(start, count) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } private class HttpResultFunc<T> implements Func1<HttpResult<T>,T>{ @Override public T call(HttpResult<T> httpResult) { return httpResult.getSubjects(); } }}
package ledon.com.retrofitdemo.api;import ledon.com.retrofitdemo.MovieBean;import retrofit2.Call;import retrofit2.http.GET;import retrofit2.http.Query;import rx.Observable;public interface MovieService { @GET("top250") Observable<MovieBean> getTopMovie(@Query("start")int start, @Query("count")int count);}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_title" android:textSize="20dp" android:text="这个杀手不太冷"/> <ImageView android:layout_gravity="center" android:id="@+id/iv" android:layout_width="100dp" android:layout_height="100dp" android:src="@mipmap/ic_launcher"/><TextView android:id="@+id/tv_name" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:text="主演:呵呵哈哈哈"/></LinearLayout>
看完上述内容,你们对如何在Android中利用Retrofit与Rxjava实现网络请求有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网精选频道,感谢大家的支持。
--结束END--
本文标题: 如何在Android中利用Retrofit与Rxjava实现网络请求
本文链接: https://lsjlt.com/news/225011.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0