Android聊天软件开发(基于网易云IM即时通讯)——注册账号(二)

OKhttp封装

IRequest

package heath.com.chat.OKhttp;

import java.util.Map;

public interface IRequest {
    public static final String POST = "POST";
    public static final String GET = "GET";
    public static final String DELETE = "DELETE";
    public static final String PUT = "PUT";

    /**
     *  请求方式
     * @param method
     */
    void setMethod(String method);

    /**
     *  指定请求头
     * @param header
     */
    void setHeader(Map<String,String> header);

    /**
     *  指定请求信息
     * @param body
     */
    void setBody(Map<String,Object> body);

    /**
     * 提供给执行库请求行URL
     * @return
     */
    String getUrl();

    /**
     * 提供给执行库请求行URL
     * @return
     */
    Map<String,String> getHeader();

    /**
     *  请求体
     * @return
     */
    Map<String,Object> getBody();

}

IHttpClient

package heath.com.chat.OKhttp;

import java.io.File;
import java.util.Map;

public interface IHttpClient {

    IResponse get(IRequest request);

    /**
     *  json格式的post
     * @param request
     * @return
     */
    IResponse post(IRequest request);

    /**
     *  表单类型的post
     * @param request
     * @param map
     * @param file
     * @return
     */
    IResponse upload_image_post(IRequest request, Map<String, Object> map, File file);
    IResponse delete(IRequest request);
    IResponse put(IRequest request);
}

IResponse

package heath.com.chat.OKhttp;

public interface IResponse {

    /**
     *  响应码
     * @return
     */
    int getCode();

    /**
     *  返回的数据
     * @return
     */
    String getData();
}

RequestImpl

package heath.com.chat.OKhttp.impl;

import java.util.Map;

import heath.com.chat.OKhttp.IRequest;

public class RequestImpl implements IRequest {

    private String method = POST;
    private String url;
    private Map<String, String> header;
    private Map<String, Object> body;

    public RequestImpl(String url) {
        /**
         *  初始化公共参数和头部信息
         */
        this.url = url;
    }

    @Override
    public void setMethod(String method) {
        this.method = method;
    }

    @Override
    public void setHeader(Map<String, String> header) {
        this.header = header;
    }

    @Override
    public void setBody(Map<String, Object> body) {
        this.body = body;
    }

    @Override
    public String getUrl() {
        if (GET.equals(method)) {
            // 组装post请求参数
            for (String key : body.keySet()) {
                url = url.replace("${" + key + "}", body.get(key).toString());
            }
        }
        return url;
    }

    @Override
    public Map<String, String> getHeader() {
        return header;
    }

    @Override
    public Map<String,Object> getBody() {
        // 组装post请求参数
        return body;
    }
}

OkHttpClientImpl

package heath.com.chat.OKhttp.impl;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import heath.com.chat.OKhttp.IHttpClient;
import heath.com.chat.OKhttp.IRequest;
import heath.com.chat.OKhttp.IResponse;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpClientImpl implements IHttpClient {
    OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .build();

    @Override
    public IResponse get(IRequest request) {
        /**
         *  解析业务参数
         */
        // 指定请求方式
        request.setMethod(IRequest.GET);
        Map<String, String> header = request.getHeader();
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet()) {
            builder.header(key, header.get(key));
        }
        builder.url(request.getUrl()
        ).get();
        Request okRequest = builder.build();
        return execute(okRequest);
    }

    @Override
    public IResponse post(IRequest request) {
        request.setMethod(IRequest.POST);
        Map<String, Object> body = request.getBody();
        FormBody.Builder builderBody = new FormBody.Builder();
        for (String key : body.keySet()) {
            builderBody.add(key, (String) body.get(key));
        }
        RequestBody requestBody = builderBody.build();
        Map<String, String> header = request.getHeader();
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet()) {
            builder.header(key, header.get(key));
        }
        builder.url(request.getUrl())
                .post(requestBody);
        Request okRequest = builder.build();
        return execute(okRequest);
    }

    @Override
    public IResponse upload_image_post(IRequest request, Map<String, Object> map, File file) {
        /**
         *  实现文件上传
         */
        request.setMethod(IRequest.POST);
        MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
        MultipartBody.Builder requestBody = new MultipartBody
                .Builder().setType(MultipartBody.FORM);
        if (file != null) {
            requestBody.addFormDataPart("image", file.getName(),
                    RequestBody.create(MEDIA_TYPE_IMAGE, file));
        }
        if (map != null) {
            // map 里面是请求中所需要的 key 和 value
            for (Map.Entry entry : map.entrySet()) {
//                requestBody.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
            }
        }
        Map<String, String> header = request.getHeader();
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet()) {
            builder.header(key, header.get(key));
        }
        builder.url(request.getUrl())
                .post(requestBody.build());
        Request okRequest = builder.build();
        return execute(okRequest);
    }

    @Override
    public IResponse delete(IRequest request) {
        request.setMethod(IRequest.DELETE);
        Map<String, String> header = request.getHeader();
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet()) {
            builder.header(key, header.get(key));
        }
        builder.url(request.getUrl())
                .delete(null);
        Request okRequest = builder.build();
        return execute(okRequest);
    }

    @Override
    public IResponse put(IRequest request) {
        request.setMethod(IRequest.PUT);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, request.getBody().toString());

        Map<String, String> header = request.getHeader();
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet()) {
            builder.header(key, header.get(key));
        }
        builder.url(request.getUrl())
                .put(requestBody);
        Request okRequest = builder.build();
        return execute(okRequest);
    }

    private IResponse execute(Request request) {
        ResponseImpl commonResponse = new ResponseImpl();
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            // 设置状态码
            commonResponse.setCode(response.code());
            String body = response.body().string();
            // 设置响应数据
            commonResponse.setData(body);
        } catch (IOException e) {
            e.printStackTrace();
            commonResponse.setCode(ResponseImpl.STATE_UNKNOW_ERROR);
            commonResponse.setData(e.getMessage());
        }
        return commonResponse;
    }
}

ResponseImpl

package heath.com.chat.OKhttp.impl;

import heath.com.chat.OKhttp.IResponse;

public class ResponseImpl implements IResponse {
    public static final int STATE_UNKNOW_ERROR = 100001;
    public static int STATE_OK = 200;
    private int code;
    private String data;

    @Override
    public String getData() {
        return data;
    }
    @Override
    public int getCode () {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public void setData(String data) {
        this.data = data;
    }

}

计算并获取checkSum

CheckSumBuilder

package heath.com.chat.utils;

import java.security.MessageDigest;

public class CheckSumBuilder {
    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}

请求头参数

image

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:background="@color/deepskyblue">

            <LinearLayout
                android:id="@+id/ll_return"
                android:layout_width="44sp"
                android:layout_height="44sp"
                android:gravity="center_vertical"
                >

                <ImageView
                    android:layout_width="24sp"
                    android:layout_height="24sp"
                    android:src="@drawable/return1"
                    android:layout_marginStart="20dp"
                    android:contentDescription="@string/tv_icon_des"
                    />

            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tv_register1"
                android:textColor="@color/white"
                android:textSize="20sp"
                android:layout_marginStart="20dp"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="80dp"
            android:orientation="vertical" >

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginBottom="40dp"
                android:src="@drawable/logo" />

            <heath.com.chat.utils.ClearEditText
                android:textCursorDrawable="@drawable/cursor_color"
                android:id="@+id/et_account"
                android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:theme="@style/MyEditText"
                android:inputType="number"
                android:textColorHint="@color/gainsboro"
                android:textColor="@color/white"
                android:maxLength="11"
                android:hint="@string/et_mobile_hint" />

            <heath.com.chat.utils.ClearEditText
                android:textCursorDrawable="@drawable/cursor_color"
                android:id="@+id/et_passwords"
                android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:theme="@style/MyEditText"
                android:inputType="textPassword"
                android:textColorHint="@color/gainsboro"
                android:textColor="@color/white"
                android:hint="@string/et_passwords_hint" />

            <Button
                android:id="@+id/btn_register"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:background="@color/deepskyblue"
                android:layout_marginTop="15dp"
                android:text="@string/tv_register"
                android:textColor="@color/white"

                />

        </LinearLayout>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_loading"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_gravity="center"
        android:background="@drawable/shape_label_clarity_black">

        <com.github.ybq.android.spinkit.SpinKitView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/pb_loading"
            style="@style/SpinKitView.Large.Circle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:SpinKit_Color="@color/white" />

        <TextView
            android:id="@+id/tv_loading_text"
            android:layout_below="@id/pb_loading"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            />

    </RelativeLayout>

</FrameLayout>

RegisterActivity

package heath.com.chat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import heath.com.chat.OKhttp.IHttpClient;
import heath.com.chat.OKhttp.IRequest;
import heath.com.chat.OKhttp.IResponse;
import heath.com.chat.OKhttp.impl.OkHttpClientImpl;
import heath.com.chat.OKhttp.impl.RequestImpl;
import heath.com.chat.utils.Common;
import heath.com.chat.utils.LoadingUtils;
import heath.com.chat.utils.ThreadUtils;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout mLlReturn;
    private Button mBtnRegister;
    private EditText mEtAccount;
    private EditText mEtpassword;
    private LoadingUtils loadingUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        init();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        mLlReturn = this.findViewById(R.id.ll_return);
        mBtnRegister = this.findViewById(R.id.btn_register);
        mEtAccount = this.findViewById(R.id.et_account);
        mEtpassword = this.findViewById(R.id.et_passwords);
        loadingUtils = new LoadingUtils(RegisterActivity.this, "注册中");

    }

    private void init() {
        loadingUtils.creat();
    }

    private void initListener() {
        mLlReturn.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        final String account = mEtAccount.getText().toString();
        final String password = mEtpassword.getText().toString();
        switch (view.getId()) {
            case R.id.ll_return:
                finish();
                break;
            case R.id.btn_register:
                if (password.length() >= 6) {
                    loadingUtils.show();
                    register(account, password);
                } else {
                    Toast.makeText(this, "密码少于6位", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void register(final String account, final String password) {
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Bundle data = new Bundle();
                try {
                    Map<String,Object> parameter = new HashMap<>();
                    parameter.put("accid", account);
                    parameter.put("name", account);
                    parameter.put("token", password);
                    Map<String,String> head = Common.getHead();
                    IRequest request = new RequestImpl("https://api.netease.im/nimserver/user/create.action");
                    //设置请求头,这里要几个就setHeader几次
                    request.setHeader(head);
                    // 设置请求体 同上
                    request.setBody(parameter);
                    // 获取一个okhttpclient实例
                    IHttpClient mHttpClient = new OkHttpClientImpl();
                    // 得到服务器端返回的结果
                    IResponse response = mHttpClient.post(request);
                    JSONObject returnObj = new JSONObject(response.getData());
                    Log.d("console", "回调: " + returnObj.toString());
                    int code = (int) returnObj.get("code");
                    switch (code) {
                        case 200:
                            message.what = 200;
                            data.putSerializable("Msg", Common.MSG_REGISTER_SUCCESS);
                            break;
                        case 414:
                            message.what = 414;
                            data.putSerializable("Msg", Common.MSG_REGISTER_HAVE_PHONE);
                            break;
                        default:
                            message.what = 1000;
                            data.putSerializable("Msg", Common.MSG_REGISTER_ERROR);
                            break;
                    }
                    message.setData(data);
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    data.putSerializable("Msg",
                            Common.MSG_REGISTER_ERROR);
                    message.setData(data);
                    handler.sendMessage(message);
                }
            }
        });
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private static class IHandler extends Handler {

        private final WeakReference<Activity> mActivity;

        public IHandler(RegisterActivity activity) {
            mActivity = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            ((RegisterActivity) mActivity.get()).loadingUtils.dismiss();
            int flag = msg.what;
            String Msg = (String) msg.getData().getSerializable(
                    "Msg");
            switch (flag) {
                case 0:
                    ((RegisterActivity) mActivity.get()).showTip(Msg);
                    break;
                case 200:
                    ((RegisterActivity) mActivity.get())
                            .showTip(Msg);
                    ((RegisterActivity) mActivity.get()).finish();
                    break;
                case 414:
                    ((RegisterActivity) mActivity.get()).showTip(Msg);
                    break;
                case 1000:
                    ((RegisterActivity) mActivity.get()).showTip(Msg);
                    break;

                default:
                    break;
            }

        }
    }

    private IHandler handler = new IHandler(this);

    private void showTip(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

}

项目下载地址:https://download.csdn.net/download/qq_32090185/11122479

下一章将介绍添加好友

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容