android OKHttp3的使用

android OKHttp3的使用

目录

1添加网络权限 1

2导入okhttp3架包(在build.gradel(app)) 1

3新建Net类用来放网址 1

4新建MathTools类,用来进行md5编码 1

5. 2

6. 全部代码 4

7. 在loginActivity.java添加回调函数 6

 

1添加网络权限


<uses-permission android:name="android.permission.INTERNET" />

2导入okhttp3架包(在build.gradel(app))

//网络请求的架包
implementation 'com.squareup.okhttp3:okhttp:3.8.1'

3新建Net类用来放网址

public class Net {
    public final  static String TEACHER="http://111.211.207.1107:800/hh/";//老师登录地址
    public final  static String STUDENT="http://111.211.207.1107:800/hh/";//学生登录地址
    public final  static String T_LOGIN=TEACHER+"Firstlogin";
    public final  static String S_LOGIN=STUDENT+"Firstlogin";
}

4新建MathTools类,用来进行md5编码

package com.example.a11699.sdsyu.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MathTools {
    public static int findMax(int[] numbers){
        int max = Integer.MIN_VALUE;
        if(numbers.length>=0){
            for(int i=0;ilength;i++){
                if(numbers[i]>max){
                    max = numbers[i];
                }
            }
            return max;
        }else{
            return 0;
        }
    }
    public static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }
}

 

5.

这里假设有登录账号 name=admin 密码 password=123

//拼接网址

String url=Net.S_LOGIN+”?s_xuehao=”+name+”&password=”+password;

//打印输出看下

Log.i(“zjc”,url);//  http://111.211.207.1107:800/hh/?s_xuehao=admin&password=123

OkHttpClicent okHttpClient=new OkHttpClient();

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) {
/*

这里请求失败的原因有两个

  1. 你的网址有错误,要么服务器没开
  2. 你访问的网址是http打头的。当你的连接是http打头的话,你要在APplicationContext.xml

添加android:usesCleartextTraffic="true"

android OKHttp3的使用_第1张图片

*/

Log.i("zjc","网络请求失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {

   Log.i(“zjc”,”请求成功”);

//拿到返回来的json串

   String responseData=response.body().string();//注意这里一定要用.string

   try{

  JSONbject jsonObject=new JSONObject(responseData);

  Log.i(“zjc”,responseData);

/*

 学校端返回的数据是:
// 没数据的时候{"Firstlogin":{}}
// 有数据的时候:
//{"Firstlogin":{"stu_id":"201604070101","token":"a3c5f24c062c4b0d24b03a3d4efe1919"}}
//

JSONObject jsonObject1=jsonObject.getJSONObject(“Firstlogin”);

try{

String stu_id=jsonObject1.getString(“stu_id”);

String password=jsonObject.getString(“token”);

//在loginActivity定义了loginCallback方法

loginActivity.loginCallback(sti_id,password);

}catch(Exception e){

//在loginActivity定义了loginlback方法

loginActivity.loginBack();

Log.i(“zjc”,”没有这项值”);

}

*/

}catch(JSONException e){

  Log.i(“zjc”,”失败”);

}

});

  1. 全部代码

package com.example.a11699.sdsyu.dao.imp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ShareActionProvider;
import android.widget.Toast;

import com.example.a11699.sdsyu.MyApplication;
import com.example.a11699.sdsyu.activities.LoginActivity;
import com.example.a11699.sdsyu.activities.MainActivity;
import com.example.a11699.sdsyu.imp.userService;
import com.example.a11699.sdsyu.internet.Net;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class userServiceDaoImp implements userService {
    private LoginActivity loginActivity;
    public userServiceDaoImp(LoginActivity loginActivity) {
        this.loginActivity=loginActivity;
    }
    @Override
    public void loginValidate(final String username, final String password) {
        Handler handler=new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                //响应的网址
                String url= Net.S_LOGIN+"?s_xuehao="+username+"&s_pwd="+password;
                Log.i("zjc",url);

                OkHttpClient okHttpClient=new OkHttpClient();
                final Request request=new Request.Builder().url(url).build();//访问不同的url在这改
                Call call=okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("zjc","网络请求失败");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("ZJC","请求成功");
                        String responseData=response.body().string();
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            Log.i("zjc",responseData);
                            //
                            // *
                            // 学校端返回的数据是:
                            // 没数据的时候{"Firstlogin":{}}
                            // 有数据的时候:
                            //{"Firstlogin":{"stu_id":"201604070101","token":"a3c5f24c062c4b0d24b03a3d4efe1919"}}
                            //
                            JSONObject jsonObject1=jsonObject.getJSONObject("Firstlogin");
                            try{
                                String stu_id=jsonObject1.getString("stu_id");//拿到登录着的id

                                String password=jsonObject1.getString("token");

                                loginActivity.loginCallback(stu_id,password);//判断登录情况
                            }catch(Exception e){
                                loginActivity.loginBack();
                                Log.i("zjc","没这项值");
                            }
                    /*
                   可以解析json里的值
                   JSONObject jsonArray=jsonObject.getJSONObject("data");//学校端返回的数据是{"data":{}}
                    String token=jsonArray.getString("loginname");
                    */
                        } catch (JSONException e) {
                            Log.i("zjc","失败");
                        }
                    }
                });
            }
        });
    }
}

 

 

  1. 在loginActivity.java添加回调函数

//成功的回调函数
public  void loginCallback(String name,String password){
    editor.putString("stu_id",name);
    editor.putString("token",password);
    editor.commit();
    Looper.prepare();
    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_LONG).show();
    Intent intent=new Intent(LoginActivity.this,MainActivity.class);//登录成功后跳转页面
    startActivity(intent);
    Looper.loop();
}
//失败的回调函数
public void loginBack(){
    Looper.prepare();
    Toast.makeText(LoginActivity.this,"用户名/密码错误",Toast.LENGTH_LONG).show();
    Looper.loop();
}

重点:

注意在线程中调用Toast时要加上

 Looper.prepare()  Looper.loop();

 

你可能感兴趣的:(android OKHttp3的使用)