依赖
compile 'com.squareup.okhttp3:okhttp:3.3.0' compile 'com.google.code.gson:gson:2.6.2'
权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
activity_main.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="view.MainActivity">
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:layout_width="230dp"
android:layout_height="40dp" />
android:id="@+id/pwd"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:layout_width="230dp"
android:layout_height="40dp" />
android:layout_below="@id/pwd"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:visibility="gone"
/>
android:layout_width="match_parent"
android:gravity="center_horizontal"
android:layout_marginTop="35dp"
android:layout_height="40dp">
activity_reg.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
tools:context=".view.RegActivity">
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:layout_width="230dp"
android:layout_height="40dp" />
android:id="@+id/pwd"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:layout_width="230dp"
android:layout_height="40dp" />
android:id="@+id/reg"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="reg"/>
HttpConfig
public class HttpConfig {
public static String url= "https://www.zhaoapi.cn/user/login";
public static String reg_url = "https://www.zhaoapi.cn/user/reg";
}
HttpUtils
public class HttpUtils {
private static final String TAG = "HttpUtils-----";
private static HttpUtils httpUtils;
private final int SUCCESS = 0;
private final int ERROR = 1;
private MyHandler myHandler = new MyHandler();
private OkLoadListener okLoadListener;
public static HttpUtils getHttpUtils() {
if (httpUtils == null) {
httpUtils = new HttpUtils();
}
return httpUtils;
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
//成功
String json = (String) msg.obj;
okLoadListener.okLoadSuccess(json);
break;
case ERROR:
//失败
String error = (String) msg.obj;
okLoadListener.okLoadError(error);
break;
}
}
}
//get
public void okGet(String url) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
Request request = new Request.Builder().url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myHandler.obtainMessage();
message.what = SUCCESS;
message.obj = response.body().string();
myHandler.sendMessage(message);
}
});
}
public void setOkLoadListener(OkLoadListener okLoadListener) {
this.okLoadListener = okLoadListener;
}
//post
public void okPost(String url, Map
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
FormBody.Builder builder = new FormBody.Builder();
Set
for (String key :
keySet) {
String value = params.get(key);
builder.add(key, value);
}
FormBody formBody = builder.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myHandler.obtainMessage();
message.what = SUCCESS;
message.obj = response.body().string();
myHandler.sendMessage(message);
}
});
}
//拦截器
class MyIntercepter implements Interceptor {
//intercept 拦截
@Override
public Response intercept(Chain chain) throws IOException {
//添加公共参数
// post 取出原来所有的参数,将之加到新的请求体里面。然后让请求去执行
Request request = chain.request();
//获取请求方法
String method = request.method();
if (method.equals("GET")) {//---------------------------GET 拦截
//取出url地址
String url = request.url().toString();
//拼接公共参数
boolean contains = url.contains("?");
if (contains) {
url = url + "&source=android";
} else {
url = url + "?source=android";
}
Request request1 = request.newBuilder().url(url).build();
Response response = chain.proceed(request1);
return response;
} else if (method.equals("POST")) {//---------------------POST 拦截
RequestBody body = request.body();//请求体
if (body instanceof FormBody) {
//创建新的请求体
FormBody.Builder newBuilder = new FormBody.Builder();
for (int i = 0; i < ((FormBody) body).size(); i++) {
String key = ((FormBody) body).name(i);
String value = ((FormBody) body).value(i);
newBuilder.add(key, value);
}
//添加公共参数
newBuilder.add("source", "android");
FormBody newBody = newBuilder.build();
//创建新的请求体
Request request1 = request.newBuilder().post(newBody).build();
//去请求
Response response = chain.proceed(request1);
return response;
}
}
return null;
}
}
//上传文件(图片)
public void upLoadImage(String url, String path) {//url 要上传的地址。path 要上传的文件路径
//媒体类型
MediaType mediaType = MediaType.parse("image/*");
//multipartbody
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
File file = new File(path);
MultipartBody multipartBody = builder.addFormDataPart("file", file.getName(), RequestBody.create(mediaType, file)).build();
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).post(multipartBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "上传失败0----: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "上传成功: ");
}
});
}
}
OkLoadListener
public interface OkLoadListener {
void okLoadSuccess(String json);
void okLoadError(String error);
}
IModel
public interface IModel {
void getLoginDatas(String url, Map
void getRegDatas(String url,Map
}
LoginBean
public class LoginBean {
/**
* msg : 登录成功
* code : 0
* data : {"age":null,"appkey":"966864480f02bc12","appsecret":"8BB1E777474FEF5A2BAA31055456B374","createtime":"2018-05-08T10:28:42","email":null,"fans":null,"follow":null,"gender":null,"icon":null,"latitude":null,"longitude":null,"mobile":"13701574569","money":null,"nickname":null,"password":"8F669074CAF5513351A2DE5CC22AC04C","praiseNum":null,"token":"2A94C4B3D9148BF4D480B1982726F099","uid":14647,"userId":null,"username":"13701574569"}
*/
private String msg;
private String code;
private DataBean data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* age : null
* appkey : 966864480f02bc12
* appsecret : 8BB1E777474FEF5A2BAA31055456B374
* createtime : 2018-05-08T10:28:42
* email : null
* fans : null
* follow : null
* gender : null
* icon : null
* latitude : null
* longitude : null
* mobile : 13701574569
* money : null
* nickname : null
* password : 8F669074CAF5513351A2DE5CC22AC04C
* praiseNum : null
* token : 2A94C4B3D9148BF4D480B1982726F099
* uid : 14647
* userId : null
* username : 13701574569
*/
private Object age;
private String appkey;
private String appsecret;
private String createtime;
private Object email;
private Object fans;
private Object follow;
private Object gender;
private Object icon;
private Object latitude;
private Object longitude;
private String mobile;
private Object money;
private Object nickname;
private String password;
private Object praiseNum;
private String token;
private int uid;
private Object userId;
private String username;
public Object getAge() {
return age;
}
public void setAge(Object age) {
this.age = age;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public String getAppsecret() {
return appsecret;
}
public void setAppsecret(String appsecret) {
this.appsecret = appsecret;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public Object getEmail() {
return email;
}
public void setEmail(Object email) {
this.email = email;
}
public Object getFans() {
return fans;
}
public void setFans(Object fans) {
this.fans = fans;
}
public Object getFollow() {
return follow;
}
public void setFollow(Object follow) {
this.follow = follow;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
public Object getIcon() {
return icon;
}
public void setIcon(Object icon) {
this.icon = icon;
}
public Object getLatitude() {
return latitude;
}
public void setLatitude(Object latitude) {
this.latitude = latitude;
}
public Object getLongitude() {
return longitude;
}
public void setLongitude(Object longitude) {
this.longitude = longitude;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Object getMoney() {
return money;
}
public void setMoney(Object money) {
this.money = money;
}
public Object getNickname() {
return nickname;
}
public void setNickname(Object nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Object getPraiseNum() {
return praiseNum;
}
public void setPraiseNum(Object praiseNum) {
this.praiseNum = praiseNum;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public Object getUserId() {
return userId;
}
public void setUserId(Object userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
}
LoginListener
public interface LoginListener {
void loginSuccess(String json);
void loginError(String error);
}
ModelImpel
public class ModelImpel implements IModel{
@Override
public void getLoginDatas(String url, Map
HttpUtils httpUtils = HttpUtils.getHttpUtils ();
httpUtils.okPost (url,map);
httpUtils.setOkLoadListener (new OkLoadListener () {
@Override
public void okLoadSuccess(String json) {
Gson gson = new Gson ();
LoginBean loginBean = gson.fromJson (json, LoginBean.class);
if(loginBean.getCode ().equals ("0")){
loginListener.loginSuccess (json);
}else{
loginListener.loginError (json);
}
}
@Override
public void okLoadError(String error) {
loginListener.loginError (error);
}
});
}
@Override
public void getRegDatas(String url, Map
HttpUtils httpUtils = HttpUtils.getHttpUtils ();
httpUtils.okPost (url,map);
httpUtils.setOkLoadListener (new OkLoadListener () {
@Override
public void okLoadSuccess(String json) {
Gson gson = new Gson ();
RegBean regBean = gson.fromJson (json, RegBean.class);
if(regBean.getCode ().equals ("0")){
regListener.regSuccess (json);
}else{
regListener.regError (json);
}
}
@Override
public void okLoadError(String error) {
regListener.regError (error);
}
});
}
}
RegBean
public class RegBean {
/**
* msg : 注册成功
* code : 0
*/
private String msg;
private String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
RegListener
public interface RegListener {
void regSuccess(String json);
void regError(String error);
}
IPresenter
public interface IPresenter {
void ShowLoginToView(IModel iModel, ILoginView iLoginView);
void ShowRegToView(IModel iModel, IRegView iRegView);
}
PresenterImpel
public class PresenterImpel implements IPresenter {
@Override
public void ShowLoginToView(IModel iModel, final ILoginView iLoginView) {
Map
map.put ("mobile",iLoginView.getMobile ());
map.put ("password",iLoginView.getPwd ());
iModel.getLoginDatas (HttpConfig.url, map, new LoginListener () {
@Override
public void loginSuccess(String json) {
iLoginView.showSuccess ();
}
@Override
public void loginError(String error) {
iLoginView.showError ();
}
});
}
@Override
public void ShowRegToView(IModel iModel, final IRegView iRegView) {
Map
map.put ("mobile",iRegView.getMobile ());
map.put ("password",iRegView.getPwd ());
iModel.getRegDatas (HttpConfig.reg_url, map, new RegListener () {
@Override
public void regSuccess(String json) {
iRegView.showSuccess ();
}
@Override
public void regError(String error) {
iRegView.showError ();
}
});
}
}
ILoginView
public interface ILoginView {
String getMobile();
String getPwd();
void showSuccess();
void showError();
}
IRegView
public interface IRegView {
String getMobile();
String getPwd();
void showSuccess();
void showError();
}
MainActivity
public class MainActivity extends AppCompatActivity implements ILoginView{
private EditText name;
private EditText pwd;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
initDatas();
}
private void initDatas() {
name = findViewById (R.id.name);
pwd = findViewById (R.id.pwd);
bar = findViewById (R.id.bar);
Button login = findViewById (R.id.login);
login.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
PresenterImpel presenterImpel = new PresenterImpel ();
presenterImpel.ShowLoginToView (new ModelImpel (),MainActivity.this);
}
});
Button reg = findViewById (R.id.reg);
reg.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
startActivity (new Intent (MainActivity.this,RegActivity.class));
}
});
}
@Override
public String getMobile() {
return name.getText ().toString ();
}
@Override
public String getPwd() {
return pwd.getText ().toString ();
}
@Override
public void showSuccess() {
/* bar.set*/
bar.setVisibility (ProgressBar.VISIBLE);
Toast.makeText (MainActivity.this,"登录成功··跳转页面",Toast.LENGTH_SHORT).show ();
}
@Override
public void showError() {
bar.setVisibility (ProgressBar.GONE);
Toast.makeText (MainActivity.this,"登录失败··",Toast.LENGTH_SHORT).show ();
}
}
RegActivity
public class RegActivity extends AppCompatActivity implements IRegView{
private EditText name;
private EditText pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_reg);
initDatas();
}
private void initDatas() {
name = findViewById (R.id.name);
pwd = findViewById (R.id.pwd);
Button reg = findViewById (R.id.reg);
reg.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
PresenterImpel presenterImpel = new PresenterImpel ();
presenterImpel.ShowRegToView (new ModelImpel (),RegActivity.this);
}
});
}
@Override
public String getMobile() {
return name.getText ().toString ();
}
@Override
public String getPwd() {
return pwd.getText ().toString ();
}
@Override
public void showSuccess() {
Toast.makeText (this,"注册成功--",Toast.LENGTH_SHORT).show ();
startActivity (new Intent (RegActivity.this,MainActivity.class));
}
@Override
public void showError() {
Toast.makeText (this,"注册失败--",Toast.LENGTH_SHORT).show ();
}
}