Retrofit+OKHttp+Rxjava

MyApplication

package com.example.day07_last_net.app;

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {
    public static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }
}

MyRxApi

package com.example.day07_last_net.rxapi;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import rx.Observable;

public interface MyRxApi {
    @GET
    Observable<ResponseBody> getInfo(@Url String url, @QueryMap Map<String,Object> map);

    @POST
    Observable<ResponseBody> postInfo(@Url String url, @QueryMap Map<String,Object> map);

    @PUT
    Observable<ResponseBody> putInfo(@Url String url, @QueryMap Map<String,Object> map);
}

MyNetUtils

package com.example.day07_last_net.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.example.day07_last_net.MyBaseUrl;
import com.example.day07_last_net.app.MyApplication;
import com.example.day07_last_net.rxapi.MyRxApi;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 最终版网络工具类
 */
public class MyNetUtils {

    private MyRxApi myRxApi;

    private MyNetUtils() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        SharedPreferences lvxx = MyApplication.mContext.getSharedPreferences("lvxx", Context.MODE_PRIVATE);
                        String userId = lvxx.getString("userId", null);
                        String sessionId= lvxx.getString("sessionId",null);
                        if (TextUtils.isEmpty(userId)||TextUtils.isEmpty(sessionId)){
                            return chain.proceed(chain.request());
                        }else {
                            Request build = chain.request().newBuilder().addHeader("userId", userId)
                                    .addHeader("sessionId", sessionId)
                                    .build();
                            return chain.proceed(build);
                        }


                    }
                }).build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(MyBaseUrl.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient).build();
        myRxApi = retrofit.create(MyRxApi.class);

    }

    private static class NetHolder {
        private static final MyNetUtils netutils = new MyNetUtils();
    }

    public static MyNetUtils getInstance() {
        return NetHolder.netutils;
    }


    //get请求方式
    public void getInfo(String url, Map<String, Object> map, final MyCallBack myCallBack) {
        myRxApi.getInfo(url, map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        myCallBack.error(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            myCallBack.success(responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    //post请求方式
    public void postInfo(String url, Map<String, Object> map, final MyCallBack myCallBack) {
        myRxApi.postInfo(url, map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        myCallBack.error(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            myCallBack.success(responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
    //PUT请求方式
    public void putInfo(String url, Map<String, Object> map, final MyCallBack myCallBack) {
        myRxApi.putInfo(url, map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        myCallBack.error(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            myCallBack.success(responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
    public interface MyCallBack {
        void success(String jsonStr);

        void error(String error);
    }
}

MainActivity

package com.example.day07_last_net;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.day07_last_net.bean.User;
import com.example.day07_last_net.utils.MyNetUtils;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText Edit_User;
    private EditText Edit_Pass;
    private Button Submit_Btn;
    private SharedPreferences mSp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mSp = getSharedPreferences("lvxx", MODE_PRIVATE);
    }

    private void initView() {
        Edit_User = (EditText) findViewById(R.id.Edit_User);
        Edit_Pass = (EditText) findViewById(R.id.Edit_Pass);
        Submit_Btn = (Button) findViewById(R.id.Submit_Btn);

        Submit_Btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Submit_Btn:
                submit();
                break;
        }
    }

    private void submit() {
        // validate
        String Userstr = Edit_User.getText().toString().trim();
        if (TextUtils.isEmpty(Userstr)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            return;
        }

        String Pass = Edit_Pass.getText().toString().trim();
        if (TextUtils.isEmpty(Pass)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something
        Map<String, Object> map = new HashMap<>();
        map.put("phone", Userstr);
        map.put("pwd", Pass);

        MyNetUtils.getInstance().postInfo(MyBaseUrl.LOGIN_URL, map, new MyNetUtils.MyCallBack() {
            @Override
            public void success(String jsonStr) {
                Gson gson = new Gson();
                User user = gson.fromJson(jsonStr, User.class);
                if (user != null && user.getStatus().equals("0000")) {
                    SharedPreferences.Editor edit = mSp.edit();
                    edit.putString("userId", user.getResult().getUserId() + "");
                    edit.putString("sessionId", user.getResult().getSessionId() + "");
                    edit.commit();
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this, UpdateActivity.class));
                }
            }

            @Override
            public void error(String error) {
                Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

MyBaseUrl

package com.example.day07_last_net;

public class MyBaseUrl {
    public static final String BASE_URL = "http://172.17.8.100/small/";
    //登录的接口
    public static final String LOGIN_URL = "user/v1/login";
    //修改密码的接口
    public static final String UPDATEPASS_URL = "user/verify/v1/modifyUserPwd";
}

UpdateActivity

package com.example.day07_last_net;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.example.day07_last_net.utils.MyNetUtils;

import java.util.HashMap;
import java.util.Map;

public class UpdateActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        Map<String,Object> map = new HashMap<>();
        map.put("oldPwd","123456");
        map.put("newPwd","111111");
        MyNetUtils.getInstance().putInfo(MyBaseUrl.UPDATEPASS_URL, map, new MyNetUtils.MyCallBack() {
            @Override
            public void success(String jsonStr) {
                Toast.makeText(UpdateActivity.this, jsonStr, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void error(String error) {
                Toast.makeText(UpdateActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值