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 header);
/**
* 指定请求信息
* @param body
*/
void setBody(Map body);
/**
* 提供给执行库请求行URL
* @return
*/
String getUrl();
/**
* 提供给执行库请求行URL
* @return
*/
Map getHeader();
/**
* 请求体
* @return
*/
Map 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 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 header;
private Map body;
public RequestImpl(String url) {
/**
* 初始化公共参数和头部信息
*/
this.url = url;
}
@Override
public void setMethod(String method) {
this.method = method;
}
@Override
public void setHeader(Map header) {
this.header = header;
}
@Override
public void setBody(Map 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 getHeader() {
return header;
}
@Override
public Map 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 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 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 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 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 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 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 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
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 parameter = new HashMap<>();
parameter.put("accid", account);
parameter.put("name", account);
parameter.put("token", password);
Map 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 mActivity;
public IHandler(RegisterActivity activity) {
mActivity = new WeakReference(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
下一章将介绍添加好友