文档中心 > 阿里聚安全

数据风控-Android示例

更新时间:2017/02/14 访问次数:13919
package com.example.jaq.changwithyourname;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.alibaba.verificationsdk.demo.R;
import com.alibaba.verificationsdk.ui.IActivityCallback;
import com.alibaba.verificationsdk.ui.VerifyActivity;
import com.alibaba.verificationsdk.ui.VerifyType;
import com.alibaba.wireless.security.open.SecurityGuardManager;
import com.alibaba.wireless.security.open.securitybody.ISecurityBodyComponent;
import com.alibaba.wireless.security.open.securitybody.SecurityBodyDefine;
import com.alibaba.wireless.security.open.SecException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity {


    private static final String[] list = new String[]{
            "短信", "语音",  "划一划", "邮件","摇一摇", "滚一滚"
    };
    private static final String[] list2 = new String[]{
            "划一划", "摇一摇", "滚一滚"
    };

    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView miplView;
    private EditText mphoneView;
    private final static String LOG_TAG = "LoginActivity";
    private Spinner mySpinner;
    private Spinner mySpinnerNoServer;
    private String  ipAddress;
    private int choiseIndex=1,choiseNoServerIndex;
    private TextView mStatus;
    String  mIP,mPhone,mMail;
    private  SharedPreferences.Editor editor;
    SharedPreferences settings;
    private  String sessionid;
    private  String mStatusText;
    void saveip(String ip)
    {
        SharedPreferences mySharedPreferences= getSharedPreferences("test",
                this.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putString("ip", ip);
        editor.commit();
    }
    String getip()
    {
        SharedPreferences mySharedPreferences= getSharedPreferences("test",
                this.MODE_PRIVATE);
        return mySharedPreferences.getString("ip","");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

/*初始化无线保镖SDK*******************必选*第一步***************************************************************************************************/
        Context context = this.getApplicationContext();
//        VerifyActivity.setEnv(VerifyActivity.DAILY);
/*初始化无线保镖SDK***************************************************************************************************************************/

        this.mySpinner = (Spinner) findViewById(R.id.way);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        this.mySpinner.setAdapter(adapter);
        this.mySpinner.setSelection(0, true);
        this.mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                choiseIndex = arg2+1;
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });


        String STORE_NAME = "Settings";
        settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        editor = settings.edit();



        this.mySpinnerNoServer = (Spinner) findViewById(R.id.noserver);
        this.mStatus = (TextView) findViewById(R.id.status);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list2);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        this.mySpinnerNoServer.setAdapter(adapter);
        this.mySpinnerNoServer.setSelection(-1, true);
        this.mySpinnerNoServer.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                choiseNoServerIndex = arg2+1;
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });




        miplView = (AutoCompleteTextView) findViewById(R.id.email);
        miplView.setText(settings.getString("ip",this.getip()));


        mphoneView = (EditText) findViewById(R.id.password);
        mphoneView.setText(settings.getString("phone",""));
        mphoneView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        if (mEmailSignInButton != null) {
            mEmailSignInButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    String ip = miplView.getText().toString();
                    ipAddress = ip;
                    saveip(ip);
                    editor.putString("ip",ip);

                    String phone = mphoneView.getText().toString();
                    editor.putString("phone",phone);
                    editor.apply();
                    mMail = getmail();
                    if(mMail==null)
                    {
                        setReturnValue("验证方式不支持");
                        return;
                    }
                    mIP = miplView.getText().toString();
                    mPhone = mphoneView.getText().toString();

                    mAuthTask = new UserLoginTask(ip, phone);
                    mAuthTask.execute((Void) null);
                }
            });
        }


        mEmailSignInButton = (Button) findViewById(R.id.risk_check);
        if (mEmailSignInButton != null) {
            mEmailSignInButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    String ip = miplView.getText().toString();
                    ipAddress = ip;
                    saveip(ip);
                    VerifyType index;
                    switch (choiseNoServerIndex)
                    {
                        case 1:index=VerifyType.NOCAPTCHA;break;
                        case 2:index=VerifyType.SHAKING;break;
                        case 3:index=VerifyType.TILTBALL;break;
                        default: {
                            setReturnValue("验证方式不支持");
                            return;
                        }
                    }
                    callSDKDoVerification(index,null);
                }
            });
        }
    }

    private String readInputStreamToString(HttpURLConnection connection) {
        String result = null;
        StringBuffer sb = new StringBuffer();
        InputStream is = null;

        try {
            is = new BufferedInputStream(connection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String inputLine = "";
            while ((inputLine = br.readLine()) != null) {
                sb.append(inputLine);
            }
            result = sb.toString();
        }
        catch (Exception e) {
            result = null;
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                }
                catch (IOException e) {
                }
            }
        }

        return result;
    }


    /*调用风险采集**********第二步******************************************************************************************************/
    void onCollectionDone(String token) {
        getAuthType(token,
                mIP,
                mMail,
                mPhone);
    }

    Runnable doJAQVerfificationASync = new Runnable() {
        @Override
        public void run() {
            int timeout = 12;
            String token=null;
            try {
                int flag = SecurityBodyDefine.OPEN_SECURITYBODY_FLAG_FORMAT_GENERAL;
                int env = SecurityBodyDefine.OPEN_SECURITYBODY_ENV_ONLINE;
                HashMap<String, String> extendParam = null;
                ISecurityBodyComponent sbComponent;
                sbComponent = SecurityGuardManager
                        .getInstance(LoginActivity.this.getApplicationContext()).getSecurityBodyComp();
                token = sbComponent.getSecurityBodyDataEx(null,
                        null,
                        "0335",
                        extendParam,
                        flag,
                        env);
//                token = securityVerification.doJAQVerfificationSync(null, timeout);
                if (null != token) {
                    Log.e(LOG_TAG, String.format("spamRegisterImp Result: %s", token));
                    onCollectionDone(token);
                }


            } catch (SecException e) {

                setReturnValue("com.alibaba.wireless.security.open.SecException"+e.getErrorCode());
            }

        }
    };
/*调用风险采集***********************************************************************************************************************/





/*调用风险识别****************第三步************************************************************************************************/

    void getAuthType(String token, String ip, String mail, String phone) {
        try {
            URL url = new URL("http://" + ip + ":8080/action/wtoken=" + token + "&&mail=" + mail + "&&phone=" + phone);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();


            String dataString = readInputStreamToString(urlConnection);
            JSONObject obj = new JSONObject(dataString);

            final String strCaptcha_type=obj.optString("captcha_type");
            final String captcha_client_need_info=obj.optString("captcha_client_need_info");
            final  VerifyType type;
            switch (Integer.parseInt(strCaptcha_type))
            {
                case 1:type = VerifyType.SMS;break;
                case 2:type = VerifyType.CALL;break;
                case 3:type = VerifyType.NOCAPTCHA;break;
                case 5:type = VerifyType.SHAKING;break;
                case 6:type = VerifyType.TILTBALL;break;
                default:
                    setReturnValue("不支持");
                    return;
            }

            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // TODO: 16/6/30 这里是错的!!!!
                    callSDKDoVerification(type,captcha_client_need_info);
                }
            });
        } catch (Exception e) {
            setReturnValue(e.toString());
        }
    }
    /*****************************************************************************************************************/



/*从服务器做二次验证******第六步*********************************************************************************************************/
    Runnable verifySessionIDWithServer = new Runnable() {
        @Override
        public void run() {
            try {
                //        NSString* formaturl = @"http://%@:8080/action/sessionid=%@";
                URL url = new URL("http://" + ipAddress + ":8080/action/sessionid=" + sessionid);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(urlConnection.getInputStream());
                /**********第七步*********************************获得聚安全的返回值*/

                String dataString = readInputStreamToString(urlConnection);
                JSONObject obj = new JSONObject(dataString);
                int ret = obj.getInt("second_check_result");
                setReturnValue(ret == 1 ? "二次验证成功" : "二次验证失败");

            } catch (Exception e) {
                setReturnValue(mStatusText + "接口异常" + e.toString());
            }
        }
    };

    /*****************************************************************************************************************/
    void checkWithSessionId() {
        try {
            Thread.sleep(500);
            new Thread(verifySessionIDWithServer).start();
        } catch (InterruptedException e) {
        }
    }
    public void onResult(int retInt, Map code) {
        switch (retInt) {
            case VerifyActivity.VERIFY_SUCC:
                Log.e(LOG_TAG, (String) code.get("sessionID"));
                sessionid = (String) code.get("sessionID");
                setReturnValue("验证通过:" + (String) code.get("sessionID"));
                checkWithSessionId();
                break;
            case VerifyActivity.VERIFY_FAILED:
                Log.e(LOG_TAG, (String) code.get("errorCode"));
                Log.e(LOG_TAG, (String) (null != code.get("errorMsg") ? code.get("errorMsg") : ""));
                VerifyActivity.finishVerifyUI();
                setReturnValue((String) (null != code.get("errorMsg") ? code.get("errorMsg") : ""));
                break;
        }
    }



    /*风险验证********************第四步***************************************************************************************************/
    public void callSDKDoVerification(VerifyType selectedIndex,String data) {
        if (data==null) {
//**********************************不进行风险采集情况下的风险验证******************************************************************************************
//
//
//
            VerifyActivity.startSimpleVerifyUI(LoginActivity.this, selectedIndex,"0335",null,new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {
                    LoginActivity.this.setReturnValue("操作取消");
                }

                /*风险验证回调***************第五步********************************************************************************************************/
                @Override
                public void onResult(int retInt, Map code) {
                    LoginActivity.this.onResult(retInt, code);
                }
            });
        }else
        {
            Map<String, String> params = new HashMap<>();
            //设置params,目前只需设置 VerifyActivity.APP_DATA
            params.put(VerifyActivity.APP_DATA, data);
            VerifyActivity.startVerifyUI(LoginActivity.this,params,selectedIndex, "0335",null,new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {
                    LoginActivity.this.setReturnValue("操作取消");
                }

                /*风险验证回调***************第五步********************************************************************************************************/
                @Override
                public void onResult(int retInt, Map code) {
                    LoginActivity.this.onResult(retInt, code);
                }
            });

        }

    }
/*风险验证************************************************************************************************************************/



    public static final int      MSAuthTypeSms=1,
            MSAuthTypeCall=2,
            MSAuthTypeSlide=3,
            MSAuthTypeMail=4,
            MSAuthBallShake=5,
            MSAuthBallRoll=6;

    void setReturnValue(final String sxxx)
    {
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                mStatusText = sxxx;
                mStatus.setText(sxxx);
            }
        });
    }
    String getmail()
    {
        String mail = null;
        switch (choiseIndex) {
            case MSAuthTypeSms:
                mail = "test_sms@test.com";
                break;
            case MSAuthTypeCall:
                mail = "test_phone@test.com";
                break;

            case MSAuthTypeSlide:
                mail = "test_hua@test.com";
                break;
            case MSAuthBallShake:
                mail = "test_shake@test.com";
                break;
            case MSAuthBallRoll:
                mail = "test_gun@test.com";
                break;
        }
        return mail;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            try {
                // Simulate network access.
                Thread.sleep(500);
                new Thread(doJAQVerfificationASync).start();
            } catch (InterruptedException e) {
                return false;
            }
            return true;
        }


        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }
}

FAQ

关于此文档暂时还没有FAQ
返回
顶部