RetrolFit+rxjava + okHttp與服務 互動的例子+取消retrolfit網路請求
本demo在前一個demo有基礎上新增了一個資料封裝與取消http請求的操作,其他無異,歡迎各位大神批評指正!!
1.retrolfit網路請求介面類
- package com.example.yourdream.retrofitdemo;
- import data.HttpResult;
- import data.UserInfo;
- import retrofit2.Call;
- import retrofit2.http.GET;
- import retrofit2.http.POST;
- import retrofit2.http.Query;
- import rx.Observable;
- /**
- * Created by yourdream on 2016/11/18.
- */
- public interface HttpRequest {
- /**
- * 普通的Retrolfit請求,返回的是一個Call
- * @param username
- * @param password
- * @return
- */
- @POST("WebService/index.jsp" )
- Call<UserInfo> login(@Query("username") String username, @Query("password") String password);
- /**
- * 支援rxjava,返回的是一個Observable,被觀察物件
- *
- * @param username
- * @param password
- * @return
- */
- @GET("WebService/index.jsp")
- Observable<UserInfo> loginByRxjava(@Query("username") String username, @Query("password") String password);
- /**
- * 支援rxjava,返回的是一個Observable,被觀察物件,其中資料用泛型封裝
- * @param username
- * @param password
- * @return
- */
- @GET("WebService/index.jsp")
- Observable<HttpResult<UserInfo>> loginByRxjava2(@Query("username") String username, @Query("password") String password);
- }
- package data;
- /**
- * 對於伺服器返回來的資料如果 格式上一致,可以對資料封裝成泛型類
- * 資訊格式類似這種:
- * {
- "resultCode": 0,
- "resultMessage": "成功",
- "data": {}
- }
- * Created by yourdream on 2016/11/21.
- */
- public class HttpResult<T> {
- private int resultCode; //前面2個欄位固定
- private String resultMessage;
- private T data; //泛型格式一致的資料
- public T getData() {
- return data;
- }
- public void setData(T data) {
- this.data = data;
- }
- public int getResultCode() {
- return resultCode;
- }
- public void setResultCode(int resultCode) {
- this.resultCode = resultCode;
- }
- public String getResultMessage() {
- return resultMessage;
- }
- public void setResultMessage(String resultMessage) {
- this.resultMessage = resultMessage;
- }
- }
3.測試用的使用者資訊類
- package data;
- /**
- * Created by yourdream on 2016/11/21.
- */
- public class UserInfo {
- private String password;
- private String username;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
- package utils;
- import rx.Subscription;
- /**
- * 取消retrolfit中的http請求,直接取消它的訂閱就行
- * Created by yourdream on 2016/11/22.
- */
- public class SubscribeUtils {
- /**
- * 取消訂閱
- * @param subscription
- */
- public static void unSubscribe(Subscription subscription) {
- if (subscription != null && !subscription.isUnsubscribed()) {
- subscription.unsubscribe();
- }
- }
- }
- package com.example.yourdream.retrofitdemo;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- import data.HttpResult;
- import data.UserInfo;
- import retrofit2.Call;
- import retrofit2.Callback;
- import retrofit2.Response;
- import retrofit2.Retrofit;
- import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
- import retrofit2.converter.gson.GsonConverterFactory;
- import rx.Subscriber;
- import rx.Subscription;
- import rx.android.schedulers.AndroidSchedulers;
- import rx.schedulers.Schedulers;
- import utils.SubscribeUtils;
- public class MainActivity extends Activity {
- private TextView normaltxt;
- private TextView rxjavatxt;
- private Button normalBtn;
- private Button rxjava;
- private Subscription tmpSubscription; //取消訂閱用的
- private static final String BASE_URL = "http://192.168.4.42:8080/";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- normaltxt = (TextView)findViewById(R.id.txt);
- rxjavatxt = (TextView)findViewById(R.id.rxjava_txt);
- normalBtn = (Button)findViewById(R.id.norml);
- rxjava = (Button)findViewById(R.id.rxjava);
- EventClick click = new EventClick();
- normalBtn.setOnClickListener(click);
- rxjava.setOnClickListener(click);
- }
- private class EventClick implements View.OnClickListener
- {
- @Override
- public void onClick(View view) {
- switch(view.getId())
- {
- case R.id.norml:
- requestNormal();
- break;
- case R.id.rxjava:
- requestByRxjava();
- break;
- }
- }
- }
- /**
- * Retrofit普通 請求
- */
- private void requestNormal()
- {
- Retrofit retrofit = new Retrofit.Builder()
- .addConverterFactory(GsonConverterFactory.create())
- .baseUrl(BASE_URL)
- .build();
- HttpRequest service = retrofit.create(HttpRequest.class);
- Call<UserInfo> call = service.login("liu", "123");
- call.enqueue(new Callback<UserInfo>() {
- @Override
- public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
- //請求成功操作
- normaltxt.setText("82---"+response.body().getUsername());
- }
- @Override
- public void onFailure(Call<UserInfo> call, Throwable t) {
- //請求失敗操作
- normaltxt.setText("87--"+t.getMessage());
- }
- });
- }
- /**
- * Retrofit支援rxjava的網路請求
- */
- private void requestByRxjava()
- {
- //測試一
- /* Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .build();
- HttpRequest service = retrofit.create(HttpRequest.class);
- service.loginByRxjava("liuhulai", "123")
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Subscriber<UserInfo>() {
- @Override
- public void onCompleted() {
- Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onError(Throwable e) {
- Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onNext(UserInfo movieEntity) {
- rxjavatxt.setText("124----"+movieEntity.getUsername());
- }
- });*/
- //測試二,返回的資料結果為泛型類
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .build();
- HttpRequest service = retrofit.create(HttpRequest.class);
- tmpSubscription = service.loginByRxjava2("liuhulai", "123")
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Subscriber<HttpResult<UserInfo>>() {
- @Override
- public void onCompleted() {
- Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onError(Throwable e) {
- Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onNext(HttpResult<UserInfo> userInfoHttpResult) {
- HttpResult<UserInfo> result = userInfoHttpResult;
- rxjavatxt.setText("124----"+ result.getResultMessage() +"\n"+result.getData().getUsername());
- }
- });
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- SubscribeUtils.unSubscribe(tmpSubscription); //取消訂閱請求用的
- }
- }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.yourdream.retrofitdemo.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/norml" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="普通請求"/> <Button android:id="@+id/rxjava" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="rxjava請求"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Hello World!" /> <TextView android:id="@+id/rxjava_txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Hello World!" /> </LinearLayout> </LinearLayout>
- <%@ page contentType="text/html; charset=utf-8" language="java"%>
- <%@ page import= "java.io.InputStream "%>
- <%@ page import="java.io.BufferedReader" %>
- <%@ page import="java.io.InputStreamReader" %>
- <%@ page import="java.io.PrintWriter" %>
- <%@ page import="org.json.JSONObject" %>
- <%
- System.out.println("12-------username:"+request.getParameter("username"));
- System.out.println("12-------pwd:"+request.getParameter("username"));
- /* BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
- System.out.println("14-------ReadClientInputStream........."+(br==null));
- StringBuffer sb =new StringBuffer("");
- String temp;
- while((temp=br.readLine())!=null)
- {
- sb.append(temp);
- System.out.println("21........."+temp);
- }
- br.close();
- System.out.println("ReadClientInputStream........."+sb); */
- /**
- *回傳給服務端的資料 測試一
- */
- /* JSONObject recObj= new JSONObject();
- recObj.put("username", "liuxb");
- recObj.put("password","123456");
- PrintWriter pw=response.getWriter();
- pw.write(recObj.toString());
- pw.flush();
- pw.close(); */
- /**
- *回傳給服務端的資料 測試二
- */
- JSONObject recObj= new JSONObject();
- recObj.put("resultCode", 0);
- recObj.put("resultMessage","成功");
- JSONObject data= new JSONObject();
- data.put("username", "liuxb");
- data.put("password","123456");
- recObj.put("data",data);
- PrintWriter pw=response.getWriter();
- pw.write(recObj.toString());
- pw.flush();
- pw.close();
- %>
- <html>
- <head>
- <script language="javascript">
- </script>
- </head>
- <body >
- <div>
- 提交監聽資料頁面
- </div>
- </body>
- </html>
相關文章
- Android網路請求(3) 網路請求框架OkHttpAndroid框架HTTP
- 網路請求優化之取消請求優化
- Android okHttp網路請求之Get/Post請求AndroidHTTP
- OKHttp網路請求原理流程解析HTTP
- okhttp網路請求框架的簡單使用HTTP框架
- 淺析okHttp3的網路請求流程HTTP
- OkHttp、rxJava、Retrofit聯合網路請求(一)HTTPRxJava
- OkHttp、rxJava、Retrofit聯合網路請求(二)HTTPRxJava
- Android okHttp網路請求之Json解析AndroidHTTPJSON
- okhttp 原始碼解析 - 網路協議的實現 - 請求流程: 請求的傳送與響應的接收HTTP原始碼協議
- 從網路請求過程看OkHttp攔截器HTTP
- Retrofit+okhttp+Rxjava封裝網路請求工具類HTTPRxJava封裝
- Android 網路框架之OKhttp實現https請求Android框架HTTP
- 前後端資料互動(一)——網路請求詳解後端
- Retrofit + RxJava + OkHttp 讓網路請求變的簡單-基礎篇RxJavaHTTP
- Retrofit + RxJava + OkHttp 讓網路請求變的簡單-封裝篇RxJavaHTTP封裝
- Android okHttp網路請求之檔案上傳下載AndroidHTTP
- 淺談前端與網路請求前端
- 分析移動端APP的網路請求APP
- Android網路請求(終) 網路請求框架RetrofitAndroid框架
- 取消請求的sql語句SQL
- Android okHttp網路請求之快取控制Cache-ControlAndroidHTTP快取
- Android網路請求(4) 網路請求框架VolleyAndroid框架
- Okhttp同步請求原始碼分析HTTP原始碼
- 前端傳送的請求,是如何請求到後端服務的?前端後端
- 網路請求了
- Express 原始碼分析1-(服務啟動和請求服務過程)Express原始碼
- 取消Fetch API請求API
- GraphQL.js 與服務端互動的新方式JS服務端
- SSRF 服務端請求偽造服務端
- Android中用Kotlin Coroutine(協程)和Retrofit進行網路請求和取消請求AndroidKotlin
- iOS 網路請求在 Controller 退出後是否應該被取消?iOSController
- Http請求-okhttp3基本用法HTTP
- OkHttp 原始碼分析(一)—— 請求流程HTTP原始碼
- OkHttp關於https請求的設定HTTP
- HTTP網路請求原理HTTP
- iOS原生網路請求iOS
- 網路請求圖片