本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>