• retrofit okhttp RxJava bk Gson Lambda 综合示例【配置】



        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    依赖

    注:这里没有指定支持 Lambda 表达式需要的配置
        //【retrofit2】
        compile 'com.squareup.retrofit2:retrofit:2.3.0'
        compile 'com.squareup.retrofit2:converter-gson:2.3.0'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    
        //【okhttp】
        compile 'com.squareup.okhttp3:okhttp:3.8.0'
        compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
        compile 'com.squareup.okio:okio:1.13.0'
    
        //【butterknife】
        compile 'com.jakewharton:butterknife:8.8.1'
        annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    
        //【rxjava】
        compile 'io.reactivex:rxandroid:1.1.0'
        compile 'io.reactivex:rxjava:1.1.6'

    GitHubApi

    public interface GitHubApi {
    	
    	@GET("repos/{owner}/{repo}/contributors")
    	Call<ResponseBody> contributorsBySimpleGetCall(@Path("owner") String owner, @Path("repo") String repo);
    	
    	@GET("repos/{owner}/{repo}/contributors")
    	Call<List<Contributor>> contributorsByAddConverterGetCall(@Path("owner") String owner, @Path("repo") String repo);
    	
    	@Headers({"Accept: application/vnd.github.v3.full+json", "User-Agent: RetrofitBean-Sample-App", "name:ljd"})
    	@GET("repos/{owner}/{repo}/contributors")
    	Call<List<Contributor>> contributorsAndAddHeader(@Path("owner") String owner, @Path("repo") String repo);
    	
    	@GET("search/repositories")
    	Call<RetrofitBean> queryRetrofitByGetCall(@Query("q") String owner, @Query("since") String time, @Query("page") int page, @Query("per_page") int per_Page);
    	
    	@GET("search/repositories")
    	Call<RetrofitBean> queryRetrofitByGetCallMap(@QueryMap Map<String, String> map);
    	
    	@GET("repos/{owner}/{repo}/contributors")
    	Observable<List<Contributor>> contributorsByRxJava(@Path("owner") String owner, @Path("repo") String repo);
    	
    	@GET("users/{user}")
    	Observable<User> userByRxJava(@Path("user") String user);
    	
    	@GET("/mobilesafe/shouji360/360safesis/360MobileSafe_6.2.3.1060.apk")
    	Call<ResponseBody> retrofitDownload();
    }

    MainActivity

    public class MainActivity extends ListActivity {
    	private TextView tv;
    	private static final String baseUrl = "https://api.github.com/";
    	private static final String mUserName = "square";//哪个公司【square】
    	private static final String mRepo = "retrofit";//哪个项目【retrofit】
    	private CompositeSubscription mSubscriptions = new CompositeSubscription();
    	
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		String[] array = {"1、简单完整演示retrofit的使用",
    				"2、添加Gson转换器",
    				"3、添加okHttp的日志拦截器Interceptor",
    				"4、使用自己封装的API,演示@Headers",
    				"5、演示同步请求",
    				"6、演示@Query",
    				"7、演示@QueryMap",
    				"8、最简单、完整的retrofit+rxJava示例",
    				"9、rxJava+retrofit增强",
    				"10、演示文件下载",};
    		tv = new TextView(this);// 将内容显示在TextView中
    		tv.setTextColor(Color.BLUE);
    		getListView().addFooterView(tv);
    		setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(array))));
    	}
    	
    	@Override
    	protected void onDestroy() {
    		if (mSubscriptions != null) mSubscriptions.unsubscribe();
    		super.onDestroy();
    	}
    	
    	@Override
    	protected void onListItemClick(ListView l, View v, int position, long id) {
    		switch (position + 1) {
    			case 1://简单完整演示retrofit的使用
    				requestGitHubContributorsSimple();
    				break;
    			case 2://添加Gson转换器
    				requestGitHubContributorsByConverter();
    				break;
    			case 3://添加okHttp的日志拦截器Interceptor
    				requestGitHubContributorsAddOkHttpLog();
    				break;
    			case 4://使用自己封装的API,演示@Headers
    				requestGitHubContributorsAddHeader();
    				break;
    			case 5://演示同步请求
    				requestGitHubContributorsBySync();
    				break;
    			case 6://演示@Query
    				requestQueryRetrofitByGet(false);
    				break;
    			case 7://演示@QueryMap
    				requestQueryRetrofitByGet(true);
    				break;
    			case 8://最简单、完整的retrofit+rxJava示例
    				requestGitHubContributorsByRxJava();
    				break;
    			case 9://rxJava+retrofit增强
    				requestGitHubContributorsWithFullUserInfo();
    				break;
    			case 10://演示文件下载
    				retrofitDownload();
    				break;
    		}
    	}
    	
    	/**
    	 * 1、简单示例
    	 */
    	private void requestGitHubContributorsSimple() {
    		Retrofit retrofit = new Retrofit.Builder()
    				.baseUrl(baseUrl)
    				.build();
    		GitHubApi repo = retrofit.create(GitHubApi.class);
    		Call<ResponseBody> call = repo.contributorsBySimpleGetCall(mUserName, mRepo);
    		call.enqueue(new Callback<ResponseBody>() {
    			@Override
    			public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
    				String result = null;
    				try {
    					result = response.body().string();
    					if (result == null) return;
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    				tv.setText("GitHub上对项目的贡献-1:
    ");
    				ArrayList<Contributor> list = new Gson()
    						.fromJson(result, new TypeToken<List<Contributor>>() {
    						}.getType());
    				if (list == null || list.size() == 0) return;
    				for (Contributor contributor : list) {
    					tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    				}
    			}
    			
    			@Override
    			public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
    				Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
    			}
    		});
    	}
    	
    	/**
    	 * 2、添加Gson转换器
    	 */
    	private void requestGitHubContributorsByConverter() {
    		new Retrofit.Builder()
    				.baseUrl(baseUrl)
    				.addConverterFactory(GsonConverterFactory.create())//转换器
    				.build()
    				.create(GitHubApi.class)
    				.contributorsByAddConverterGetCall(mUserName, mRepo)
    				.enqueue(new Callback<List<Contributor>>() {
    					@Override
    					public void onResponse(@NonNull Call<List<Contributor>> call, @NonNull Response<List<Contributor>> response) {
    						List<Contributor> list = response.body();
    						tv.setText("GitHub上对项目的贡献-2:
    ");
    						if (list == null || list.size() == 0) return;
    						for (Contributor contributor : list) {
    							tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    						}
    					}
    					
    					@Override
    					public void onFailure(@NonNull Call<List<Contributor>> call, @NonNull Throwable t) {
    						Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
    					}
    				});
    	}
    	
    	/**
    	 * 3、添加okHttp的日志拦截器Interceptor
    	 */
    	private void requestGitHubContributorsAddOkHttpLog() {
    		HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
    		
    		Retrofit retrofit = new Retrofit.Builder()
    				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    				.client(new OkHttpClient.Builder().addInterceptor(logInterceptor).build())
    				.baseUrl(baseUrl)
    				.addConverterFactory(GsonConverterFactory.create())
    				.build();
    		
    		retrofit.create(GitHubApi.class)
    				.contributorsByAddConverterGetCall(mUserName, mRepo)
    				.enqueue(new Callback<List<Contributor>>() {
    					@Override
    					public void onResponse(@NonNull Call<List<Contributor>> call, @NonNull Response<List<com.bqt
    							.retrofit.bean.Contributor>> response) {
    						List<Contributor> list = response.body();
    						tv.setText("GitHub上对项目的贡献-3:
    ");
    						if (list == null || list.size() == 0) return;
    						for (Contributor contributor : list) {
    							tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    						}
    					}
    					
    					@Override
    					public void onFailure(@NonNull Call<List<Contributor>> call, @NonNull Throwable t) {
    						Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
    					}
    				});
    	}
    	
    	/**
    	 * 4、使用自己封装的API,演示@Headers
    	 */
    	private void requestGitHubContributorsAddHeader() {
    		createRetrofitService(GitHubApi.class)
    				.contributorsAndAddHeader(mUserName, mRepo)
    				.enqueue(new Callback<List<Contributor>>() {
    					@Override
    					public void onResponse(@NonNull Call<List<Contributor>> call, @NonNull Response<List<com.bqt
    							.retrofit.bean.Contributor>> response) {
    						List<Contributor> list = response.body();
    						tv.setText("GitHub上对项目的贡献-4:
    ");
    						if (list == null || list.size() == 0) return;
    						for (Contributor contributor : list) {
    							tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    						}
    					}
    					
    					@Override
    					public void onFailure(@NonNull Call<List<Contributor>> call, @NonNull Throwable t) {
    					}
    				});
    	}
    	
    	/**
    	 * 5、演示同步请求
    	 */
    	private void requestGitHubContributorsBySync() {
    		final Call<List<Contributor>> call = createRetrofitService(GitHubApi.class)
    				.contributorsByAddConverterGetCall(mUserName, mRepo);
    		new Thread(() -> {
    			try {
    				Response<List<Contributor>> response = call.execute();//在子线程中请求网络
    				final List<Contributor> list = response.body();
    				runOnUiThread(() -> {
    					tv.setText("GitHub上对项目的贡献-5:
    ");
    					for (Contributor contributor : list) {
    						tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    					}
    				});
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}).start();
    	}
    	
    	/**
    	 * 6/7、演示@Query和@QueryMap
    	 */
    	private void requestQueryRetrofitByGet(boolean isQueryMap) {
    		GitHubApi mGitHubService = createRetrofitService(GitHubApi.class);
    		Call<RetrofitBean> call;
    		if (!isQueryMap) call = mGitHubService.queryRetrofitByGetCall("retrofit", "2016-03-29", 1, 3);
    		else {
    			Map<String, String> queryMap = new HashMap<>();
    			queryMap.put("q", "retrofit");
    			queryMap.put("since", "2016-03-29");
    			queryMap.put("page", "1");
    			queryMap.put("per_page", "3");
    			call = mGitHubService.queryRetrofitByGetCallMap(queryMap);
    		}
    		
    		call.enqueue(new Callback<RetrofitBean>() {
    			@Override
    			public void onResponse(@NonNull Call<RetrofitBean> call, @NonNull Response<RetrofitBean> response) {
    				RetrofitBean retrofitBean = response.body();
    				if (retrofitBean == null) return;
    				List<Item> list = retrofitBean.getItems();
    				if (list == null || list.size() == 0) return;
    				
    				tv.setText(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS", Locale.getDefault()).format(new Date()));
    				tv.append("
    total:" + retrofitBean.getTotalCount() + "
    incompleteResults:" + retrofitBean.getIncompleteResults());
    				for (Item item : list) {
    					tv.append("
    
    【name】" + item.name);
    					tv.append("
    【full_name】" + item.full_name);
    					tv.append("
    【 description】" + item.description);
    				}
    			}
    			
    			@Override
    			public void onFailure(@NonNull Call<RetrofitBean> call, @NonNull Throwable t) {
    			}
    		});
    	}
    	
    	/**
    	 * 8、最简单、完整的retrofit+rxJava示例
    	 */
    	private void requestGitHubContributorsByRxJava() {
    		createRetrofitService(GitHubApi.class)
    				.contributorsByRxJava(mUserName, mRepo)//
    				.subscribeOn(Schedulers.io())//
    				.observeOn(AndroidSchedulers.mainThread())//
    				.subscribe(new Observer<List<Contributor>>() {
    					@Override
    					public void onCompleted() {
    						Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show();
    					}
    					
    					@Override
    					public void onError(Throwable e) {
    						Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
    					}
    					
    					@Override
    					public void onNext(List<Contributor> list) {
    						tv.setText("GitHub上对项目的贡献-8:
    ");
    						for (Contributor contributor : list) {
    							tv.append(contributor.login + "    " + contributor.contributions + "
    ");
    						}
    					}
    				});
    	}
    	
    	/**
    	 * 9、rxJava+retrofit增强
    	 */
    	private void requestGitHubContributorsWithFullUserInfo() {
    		tv.setText("");
    		final GitHubApi mGitHubService = createRetrofitService(GitHubApi.class);
    		
    		Subscription subscription =
    				mGitHubService.contributorsByRxJava(mUserName, mRepo)//
    						.flatMap(new Func1<List<Contributor>, Observable<Contributor>>() {
    							//变换:将事件序列中的对象或整个序列进行加工处理,转换成不同的事件或事件序列
    							@Override
    							public Observable<Contributor> call(List<Contributor>
    									                                    contributors) {
    								//1、使用传入的事件对象创建一个 Observable 对象;
    								//2、并不发送这个 Observable,而是将它激活,于是它开始发送事件;
    								//3、创建的 Observable 发送的事件,都被汇入同一个 Observable,而这个 Observable 负责将这些事件统一交给Subscriber 的回调方法
    								return Observable.from(contributors);
    							}
    						})
    						.flatMap(new Func1<Contributor, Observable<Pair<User, Contributor>>>() {
    							@Override
    							public Observable<Pair<User, Contributor>> call(com.bqt
    									                                                .retrofit.bean.Contributor contributor) {
    								Observable<User> userObservable = mGitHubService.userByRxJava(contributor.login)
    										.filter(user -> !isEmpty(user.name) && !isEmpty(user.email));
    								return Observable.zip(userObservable, Observable.just(contributor), Pair::new);
    							}
    						})
    						.subscribeOn(Schedulers.newThread())//指定 subscribe() 发生在哪个线程,后台线程取数据,主线程显示
    						.observeOn(AndroidSchedulers.mainThread())//指定 Subscriber 的回调发生在主线程
    						.subscribe(new Observer<Pair<User, Contributor>>() {
    							@Override
    							public void onCompleted() {
    								Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show();
    							}
    							
    							@Override
    							public void onError(Throwable e) {
    								Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
    							}
    							
    							@Override
    							public void onNext(Pair<User, Contributor> pair) {
    								User user = pair.first;
    								Contributor contributor = pair.second;
    								tv.append("name:" + user.name + "
    contributions:" + contributor.contributions + "
    Email:" + user.email + "
    
    ");
    							}
    						});
    		mSubscriptions.add(subscription);
    	}
    	
    	/**
    	 * 10、演示文件下载
    	 */
    	public void retrofitDownload() {
    		//监听下载进度
    		final ProgressDialog dialog = new ProgressDialog(this);
    		dialog.setProgressNumberFormat("%1d KB/%2d KB");
    		dialog.setTitle("下载");
    		dialog.setMessage("正在下载,请稍后...");
    		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    		dialog.setCancelable(false);
    		dialog.show();
    		
    		ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
    			@Override
    			protected void onProgress(long bytesRead, long contentLength, boolean done) {
    				//在主线程中运行
    				dialog.setMax((int) (contentLength / 1024));
    				dialog.setProgress((int) (bytesRead / 1024));
    				if (done) dialog.dismiss();
    			}
    		});
    		
    		Retrofit retrofit = new Retrofit.Builder()//
    				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//
    				.addConverterFactory(GsonConverterFactory.create())//
    				.baseUrl("http://msoftdl.360.cn")
    				.client(ProgressHelper.addProgress(null).build())
    				.build();
    		
    		retrofit.create(GitHubApi.class).retrofitDownload()
    				.enqueue(new Callback<ResponseBody>() {
    					@Override
    					public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
    						try {
    							InputStream is = response.body().byteStream();
    							File file = new File(Environment.getExternalStorageDirectory(), "12345.apk");
    							FileOutputStream fos = new FileOutputStream(file);
    							BufferedInputStream bis = new BufferedInputStream(is);
    							byte[] buffer = new byte[1024];
    							int len;
    							while ((len = bis.read(buffer)) != -1) {
    								fos.write(buffer, 0, len);
    								fos.flush();
    							}
    							fos.close();
    							bis.close();
    							is.close();
    						} catch (IOException e) {
    							e.printStackTrace();
    						}
    					}
    					
    					@Override
    					public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
    					}
    				});
    	}
    	
    	public static <T> T createRetrofitService(final Class<T> service) {
    		HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY);
    		OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor);
    		Retrofit retrofit = new Retrofit.Builder()//
    				.client(ProgressHelper.addProgress(builder).build())//
    				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//
    				.addConverterFactory(GsonConverterFactory.create())//
    				.baseUrl("https://api.github.com/")//
    				.build();
    		return retrofit.create(service);
    	}
    }

    综合配置

    retrofit、okhttp、RxJava、Gson、拦截器、Header等配置
    public class H {
    	private static Interceptor buildInterceptor() {
    		final String token = AccountManager.getInstance().getToken();
    		PackageInfo packInfo = null;
    		try {
    			packInfo = App.app.getPackageManager().getPackageInfo(App.app.getPackageName(), 0);
    		} catch (PackageManager.NameNotFoundException e) {
    			e.printStackTrace();
    		}
    		final int version = packInfo == null ? 1 : packInfo.versionCode;
    		return 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", "*/*")
    						//****************************************自定义Header**************************************************
    						.addHeader("version", version + "")//app版本号
    						.addHeader("token", token == null ? "" : token)//登录后返回的token
    						.addHeader("mobile", "1")// 0-PC,1-Android,2-IOS,3-web
    						.build();
    				return chain.proceed(request);
    			}
    		};
    	}
        
    	private static Interceptor buildLogInterceptor() {
    		return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    			@Override
    			public void log(String message) {
    				L.i(message);
    			}
    		}).setLevel(HttpLoggingInterceptor.Level.BODY);//日志显示级别
    	}
        
    	private static OkHttpClient buildOkHttp() {
    		return new OkHttpClient.Builder()
    				.addInterceptor(buildHeaderInterceptor())//自定义Header
    				.addInterceptor(buildLogInterceptor())//日志拦截
                    .connectTimeout(5, TimeUnit.SECONDS)
    				.build();
    	}
    	
    	private static Gson buildGson() {
    		return new GsonBuilder()//配置你的Gson
    				.setDateFormat("yyyy-MM-dd hh:mm:ss")
    				.setPrettyPrinting()
    				.serializeNulls()
    				.create();
    	}
    	
    	private static String buildBaseUrl() {
    		switch (UrlHelper.getEnv()) {
    			case 0: // baseUlr 必须以 / 结束,不然会抛出一个IllegalArgumentException
    				return "http://test.talk.99cj.com.cn/";
    			case 1:
    				return "http://wechat.99cj.com.cn/";
    			default:
    				return "http://wechat.99cj.com.cn/";
    		}
    	}
    	
    	private static Retrofit buildRetrofit(OkHttpClient client, Converter.Factory converterFactory, CallAdapter.Factory callAdapterFactory) {
    		return new Retrofit.Builder()
    				.baseUrl(buildBaseUrl())
    				.client(client)
    				.addConverterFactory(converterFactory)//可以接收自定义的Gson,当然也可以不传
    				.addCallAdapterFactory(callAdapterFactory)
    				.build();
    	}
    	
    	private static <T> T createRetrofitService(final Class<T> service) {
    		Retrofit retrofit = buildRetrofit(buildOkHttp(), //
    				GsonConverterFactory.create(buildGson()),//
    				RxJavaCallAdapterFactory.create());//
    		return retrofit.create(service);
    	}
    	
    	public static BqtService h() {
    		return createRetrofitService(BqtService.class);
    	}
    }
    添加上述【HttpLoggingInterceptor】拦截器后会打印如下日志
    请求参数封装
    public interface BqtService {
    	/*个人中心*/  /* 如果注解中提供的url是完整的url(以http开头),则忽略baseUrl,直接讲此url将作为请求的url */
    	@GET("User") /* 如果不以/开头,则请求的url为baseUrl+注解中提供的值;否则请求的url为baseUrl的主机部分+注解中提供的值*/
    	Observable<BqtRes<User>> getUser();
    
    	/*用户购买记录*/
    	@FormUrlEncoded
    	@POST("BuyInfo/buyRecord")	/*【type】1:购买课程 2:购买观点 3:直播赞赏*/
    	Observable<BqtRes<ArrayList<MyClassBean>>> getPurchaseHistory1(@Field("user_id") int uid, @Field("page") int page, @Field("type") int type);
    }
    调用
    H.h().getUser()
    	.subscribeOn(Schedulers.newThread())//指定 subscribe() 发生在哪个线程,后台线程取数据,主线程显示
    	.observeOn(AndroidSchedulers.mainThread())//指定 Subscriber 的回调发生在主线程
    	.subscribe(new Subscriber<BqtRes<User>>() {
    		@Override
    		public void onCompleted() {
    		}
    		
    		@Override
    		public void onError(Throwable e) {
    			L.i("【onError】" + e.toString());
    		}
    		
    		@Override
    		public void onNext(BqtRes<User> response) {
    			L.i("【onNext】" + response.data.toString());//这里response.data的类型即是User
    		}
    	});
    2017-9-22

    附件列表

    • 相关阅读:
      MySQL 5.7.18 zip 文件安装过程
      Mysql 自定义随机字符串
      JAVA基本类型和引用类型
      初识JSP
      Java导出错误数据
      时序图的使用习惯
      Redis踩坑
      ES踩坑
      代码规范
      Git在公司的使用流程
    • 原文地址:https://www.cnblogs.com/baiqiantao/p/204a470eef21bfe096742aa26524febd.html
    Copyright © 2020-2023  润新知