Retrofit+RxJava 실전 로그(2) - 기본 사용
public abstract class BaseApi {
public static final String API_SERVER = " "
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
private static Retrofit mRetrofit;
protected static Retrofit getRetrofit() {
if (Retrofit == null) {
Context context = Application.getInstance().getApplicationContext();
// 30
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// , Cookies
mOkHttpClient.networkInterceptors()
.add(new CookiesInterceptor(context));
//
File cacheDirectory = new File(context.getCacheDir()
.getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
mOkHttpClient.setCache(cache);
// Retrofit
mRetrofit = new Retrofit.Builder()
//
.baseUrl(API_SERVER + "/")
// , Date
.setDateFormat("yyyy-MM-dd HH:mm:ss")
// , Gson
.addConverterFactory(ResponseConverterFactory.create())
// , RxJava
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// OKHttpClient
.client(mOkHttpClient)
.build();
}
return mRetrofit;
}
}
그리고 쿠키 차단기.
public class CookiesInterceptor implements Interceptor{
private Context context;
public CookiesInterceptor(Context context) {
this.context = context;
}
// , Cookies
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request compressedRequest = request.newBuilder()
.header("cookie", CookieUtil.getCookies(context))
.build();
Response response = chain.proceed(compressedRequest);
CookieUtil.saveCookies(response.headers(), context);
return response;
}
}
CookieUtil은 사용자 정의 해석 및 생성 방법과 SharedPreferences에 대한 액세스, 코드 요약
그리고 Api 클래스.
public class UserApi extends BaseApi{
//
private interface UserService {
//GET @FormUrlEncoded, @Query
@GET("user/user_queryProfile")
Observable queryProfile(@Query("userId") int userId);
//POST ,
@FormUrlEncoded
@POST("user/user_updateUserName")
Observable updateUserName(@Field("userName") String userName);
}
protected static final UserService service = getRetrofit().create(UserService.class);
//
public static Observable queryProfile(int userId){
return service.queryProfile(userId);
}
//
public static Observable updateUserName(String userName){
return service.updateUserName(userName);
}
}
그리고 Retrofit의 응답 메시지를 Gson을 통해 원하는 데이터 구조로 해석하여 Model 클래스에 있는 BaseResp와 UserProfileResp는 사용자 정의 모델이라고 부른다
서버 약정이 반환되는 Json 형식은
{
"result":" ,0 ",
"msg":" , ",
"userInfo":
{
"id":" id",
"userName":" "
}
}
그러면 UserProfileResp는 쓸 수 있습니다.
public class UserProfileResp {
//@SerializedName Json Key
// , Key
@SerializedName("userInfo")
private UserProfileModel userInfo;
public UserProfileModel getUserInfo() {
return userInfo;
}
}
UserProfileModel은 구체적인 데이터 구조입니다.
public class UserProfileModel {
private int userId;
private String userName;
public String getUserName(){
return userName;
}
}
주의해야 할 것은 @SerializedName을 사용하여 키 이름을 지정하지 않으면 프로젝트가 헷갈릴 때 변수 이름이 원하는 키 이름과 맞지 않게 헷갈릴 수 있습니다.따라서 이러한 모델 클래스를 하나의 프로젝트 디렉터리에 통일시키고proguard-project 파일에 배제 항목을 넣어야 합니다
// Model
-keep class com.xxx.model.xxx.** { *; }
마지막으로 실제 호출입니다.
public void getProfile(int userId){
UserApi.queryProfile(userId)
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber(){
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(UserProfileResp userProfileResp) {
}
});
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.