okhttp post提交參數完成登錄功能 保存返回的token

作爲一名android開發者,通過博客記錄自己成長的道路,以下是小白在開發實踐中的登錄功能實現的一些步驟及功能,希望對做這一部分功能的夥伴有一定的幫助

1.登錄的界面佈局

2.登錄的url、sp保存token、okhttp post請求

3.登錄的ui界面,功能代碼....


登錄界面如下,勿噴



activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/ccimgv_head"
        android:layout_width="62dp"
        android:layout_height="62dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="95dp"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#0DC5E6"
        app:civ_border_width="2dp"/>

    <TextView
        android:id="@+id/tv_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="12dp"
        android:text="用戶名"
        android:textColor="#323232"
        android:textSize="15sp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="51dp"
        android:layout_marginTop="38dp"
        android:text="手機號碼"
        android:textColor="#2D2D2D"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="37dp"
        android:layout_marginRight="37dp"
        android:layout_marginTop="4dp"
        android:background="#FFFFFF"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="8dp"
            android:src="@mipmap/registphone"/>

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="13dp"
            android:background="@null"
            android:hint="123456789"
            android:textSize="12sp"/>

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="51dp"
        android:layout_marginTop="6dp"
        android:text="密碼"
        android:textColor="#2D2D2D"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="37dp"
        android:layout_marginRight="37dp"
        android:layout_marginTop="4dp"
        android:background="#FFFFFF">

        <ImageView
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="8dp"
            android:src="@mipmap/password"/>

        <EditText
            android:id="@+id/et_psw"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="13dp"
            android:background="@null"
            android:hint="密碼"
            android:textSize="12sp"/>
    </LinearLayout>
    <!-- 登錄按鈕 -->
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="37dp"
        android:layout_marginRight="37dp"
        android:layout_marginTop="15dp"
        android:background="@drawable/shape_login_bg"
        android:text="@string/login"
        android:textColor="#FDFDFD"
        android:textSize="14sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_marginLeft="37dp"
        android:layout_marginRight="37dp"
        android:layout_marginTop="17dp">

        <Button
            android:id="@+id/btn_user_register"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:text="用戶註冊"
            android:textColor="#9F9F9F"
            android:textSize="12sp"/>

        <View
            android:layout_width="1dp"
            android:layout_height="14dp"
            android:layout_gravity="center_horizontal"
            android:background="#DCDCDC"/>

        <Button
            android:id="@+id/btn_forget_psw"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:text="忘記密碼"
            android:textColor="#9F9F9F"
            android:textSize="12sp"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@mipmap/background"/>

</LinearLayout>

okhttp post請求登錄

LoginActivity

package fho.nak.jeekup.nakfho.ui.loginandregister;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import fho.nak.jeekup.nakfho.MainActivity;
import fho.nak.jeekup.nakfho.R;
import fho.nak.jeekup.nakfho.base.BaseActivity;
import fho.nak.jeekup.nakfho.bean.ResultData;
import fho.nak.jeekup.nakfho.utils.MD5Utils;
import fho.nak.jeekup.nakfho.utils.PreferenceUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @創建者 Jimven
 * @創建時間 2017/7/21/0021  11:35
 */

/**
 * 登錄界面
 */
public class LoginActivity extends BaseActivity {
    String loginUrl    = "http://www.xxx";
    @Bind(R.id.ccimgv_head)
    CircleImageView mCcimgvHead;
    @Bind(R.id.tv_username)
    TextView        mTvUsername;
    @Bind(R.id.et_phone)
    EditText        mEtPhone;
    @Bind(R.id.et_psw)
    EditText        mEtPsw;
    @Bind(R.id.btn_login)
    Button          mBtnLogin;
    @Bind(R.id.btn_user_register)
    Button          mBtnUserRegister;
    @Bind(R.id.btn_forget_psw)
    Button          mBtnForgetPsw;
    private MediaType mMediaType;
    private String mToken;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void setUpView() {
        initView();
        initData();
        initEvent();

    }

    //初始化組件
    private void initView() {

    }

    //初始化數據
    private void initData() {

    }

    //初始化事件
    private void initEvent() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({  R.id.btn_login, R
            .id.btn_user_register, R.id.btn_forget_psw})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //登錄操作
                login();

                break;
            case R.id.btn_user_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.btn_forget_psw:
                startActivity(new Intent(this, ResetpswActivity.class));
                break;
        }
    }

    //登錄操作
    private void login() {
        final String phone = mEtPhone.getText().toString();
        final String userPsw = mEtPsw.getText().toString();
        final String md5Password = MD5Utils.md5Password(userPsw);//加密MD5
        //判斷是否非空
        if (!TextUtils.isEmpty(temphone) && !TextUtils.isEmpty(tempsw)) {//都不爲空
            //請求數據

            OkHttpClient client = new OkHttpClient();
            final JSONObject jsonObject = new JSONObject();

            try {//提交的參數
                jsonObject.put("loginName", phone);
                jsonObject.put("password", md5Password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mMediaType = MediaType.parse("application/json; charset=utf-8");
            final RequestBody requestBody = RequestBody.create(mMediaType, jsonObject.toString());
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(LoginUrl)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //請求失敗
                    Log.i("請求情況:", "請求失敗");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Log.i("響應狀態", "響應成功");
                        String loginBody = response.body().string();
                        Gson gson = new Gson();
                        ResultData loginData = gson.fromJson(loginBody, ResultData.class);

                        String loginResultCode = loginData.getResultCode();
                        Log.i("返回狀態碼", loginResultCode);
                        //響應成功,判斷狀態碼
                        if (loginResultCode.equals("100")) {
                            Log.i("登錄狀態", "登錄成功");
                            //獲取tokenxz
                            Object data = loginData.getData();
                            String data1 = data.toString();
                          JSONObject jsonObject1 = null;
                            try {
                                jsonObject1 = new JSONObject(data1);
                                mToken = jsonObject1.optString("token");
                                Log.i("打印token", mToken);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }                  
			//保存token
			//用sp工具保存
			PreferenceUtils.putString(getApplicationContext(), "token", mToken);
//登錄成功,跳到主界面 startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); } else if (loginResultCode.equals("500")) { Log.i("登錄狀態", "登錄失敗"); Toast.makeText(LoginActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show(); } else { Log.i("Jimven", "其他"); } } else { Log.i("響應情況:", "響應失敗"); } } }); } else { Toast.makeText(LoginActivity.this, "請填寫完整的信息", Toast.LENGTH_SHORT).show(); } }}

附上sp工具代碼

PreferenceUtils.java


package fho.nak.jeekup.nakfho.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * sp工具類
 */
public class PreferenceUtils {

   public static void putString(Context context, String key, String value){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      sp.edit().putString(key, value).commit();
   }

   public static String getString(Context context, String key, String defValue){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return sp.getString(key, defValue);
   }
   public static String getString(Context context, String key){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return getString(context,key,"");
   }

   public static void putBoolean(Context context, String key, boolean value){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      sp.edit().putBoolean(key, value).commit();
   }

   public static boolean getBoolean(Context context, String key, boolean defValue){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return sp.getBoolean(key, defValue);
   }

   public static boolean getBoolean(Context context, String key){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return getBoolean(context,key,false);
   }

   public static void putInt(Context context, String key, int value){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      sp.edit().putInt(key, value).commit();
   }

   public static int getInt(Context context, String key, int defValue){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return sp.getInt(key, defValue);
   }

   public static int getInt(Context context, String key){
      SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
      return getInt(context,key,-1);
   }
 
}

以上簡單的登錄功能就完成了,希望對大家有幫助,也希望大家能夠多多交流,一起成長

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章