-
-
Save LOG-TAG/1d786f72bf6ba59abef0 to your computer and use it in GitHub Desktop.
Retrofit 2.0 RxJava Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dependencies { | |
compile 'io.reactivex:rxjava:1.0.12' | |
compile 'com.squareup.okhttp:okhttp:2.5.0' | |
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1' | |
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1' | |
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Logging with Retrofit | |
* RxJava with Retrofit | |
* | |
*/ | |
public class Sample { | |
public static void main(String[] args) throws Exception{ | |
OkHttpClient client = new OkHttpClient(); | |
client.interceptors().add(new LoggingInterceptor()); | |
Retrofit retrofit = new Retrofit.Builder().baseUrl(IPService.END).client(client) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) | |
.build(); | |
retrofit.create(IPService.class) | |
.getIPInfo("58.19.239.11").filter(jsonObject -> jsonObject.get("code").getAsInt()==0) | |
.map(jsonObject1 -> jsonObject1.get("data")) | |
.subscribe(System.out::println); | |
return; | |
} | |
interface IPService { | |
String END = "http://ip.taobao.com"; | |
@GET("/service/getIpInfo.php") Observable<JsonObject> getIPInfo(@Query("ip") String ip); | |
} | |
static class LoggingInterceptor implements Interceptor { | |
@Override public Response intercept(Chain chain) throws IOException { | |
Request request = chain.request(); | |
long t1 = System.nanoTime(); | |
System.out.println( | |
String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), | |
request.headers())); | |
Response response = chain.proceed(request); | |
long t2 = System.nanoTime(); | |
System.out.println( | |
String.format("Received response for %s in %.1fms%n%s", response.request().url(), | |
(t2 - t1) / 1e6d, response.headers())); | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment