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' };
}
请求头参数
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
下一章将介绍添加好友