这个是基于eclipse写的一个ShareSDK的短信验证
不说太多直接上代码了,里面的注释清晰
这是Activity
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;
public class MainActivity extends ActionBarActivity implements OnClickListener {
//sharesdk创建应用时给的两个参数,用自己的APP_KEY和APP_SECRET
private static final String APP_KEY = "XXXXXXXXXXX";
private static final String APP_SECRET = "XXXXXXXXXXX";
private EventHandler eh;
private EditText et_phone, et_code;
private Button bt_send, bt_check_code;
private String phone, code;
Observable<String> myObservable;
Subscriber<String> mySubscribe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initListener();
doWork();
sdkCallback();
}
private void initListener() {
bt_send.setOnClickListener(this);
bt_check_code.setOnClickListener(this);
}
private void initView() {
// TODO Auto-generated method stub
et_phone = (EditText) findViewById(R.id.et_phone);
et_code = (EditText) findViewById(R.id.et_code);
bt_send = (Button) findViewById(R.id.bt_send);
bt_check_code = (Button) findViewById(R.id.bt_check_code);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
phone = et_phone.getText().toString().trim();
code = et_code.getText().toString().trim();
switch (view.getId()) {
case R.id.bt_send:// 获取短信验证
SMSSDK.getVerificationCode("86", phone);
break;
case R.id.bt_check_code:// 把短信里的验证码提交到服务器
// SMSSDK.submitVerificationCode("86", phone, code);
RxJavaMethod2();
break;
default:
break;
}
}
/**
* 请求网络要开一个新线程
* 利用RxJava进行异步访问网络
* 看不懂的就自行去补习一下
*/
public void RxJavaMethod2() {
myObservable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> sub) {
sub.onNext("这是一个简单的rxjava例子");
sub.onCompleted();
}
});
// 如果没有发生异常就会先执行onNext,再执行onCompleted,只要有异常就会调用onError
mySubscribe = new Subscriber<String>() {
//操作
@Override
public void onNext(String s) {
//返回信息
String result = requestData(
"https://webapi.sms.mob.com/sms/verify", "appkey="
+ APP_KEY + "&phone=" + phone
+ "&zone=86&code=" + code);
// 参考返回码:http://wiki.mob.com/android-api-错误码参考/
//这个是验证成功时返回的 ---- {status:200}
System.out.println("result=" + result);//打印 返回信息
System.out.println("RxJavaMethod--------onNext");
}
//操作完成
@Override
public void onCompleted() {
System.out.println("RxJavaMethod--------onCompleted");
}
//出错调用
@Override
public void onError(Throwable e) {
System.out.println("RxJavaMethod--------onError");
}
};
myObservable.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread()).subscribe(mySubscribe);
}
/**
* 初始化sdk
*/
public void doWork() {
SMSSDK.initSDK(this, APP_KEY, APP_SECRET);
// sdkUI();
}
/**
* 这个是sdk提供的ui
*/
public void sdkUI() {
RegisterPage page = new RegisterPage();// 这个是sdk自带的ui
page.setRegisterCallback(new EventHandler() {
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) {
HashMap<String, Object> phoneMap = (HashMap<String, Object>) data;
String country = (String) phoneMap.get("country");
String phone = (String) phoneMap.get("phone");
// 提交用户信息,这个方法是获取了手机后,你想采取的操作。
// registerUser(country, phone);
System.out.println(country + phone);
}
}
});
page.show(this);
}
/**
* 提交的回调
*/
public void sdkCallback() {
eh = new EventHandler() {
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) {
// 回调完成
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
// 提交验证码成功
System.out.println("成功!" + data);
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
// 获取验证码成功
System.out.println("获取验证码成功" + data);
} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
// 返回支持发送验证码的国家列表
System.out.println("支持发送国家列表" + data);
}
} else {
((Throwable) data).printStackTrace();
}
}
};
SMSSDK.registerEventHandler(eh); // 注册短信回调
}
/**
* 短信服务器端验证 发起https 请求
*
* @param address
* @param m
* @return
*/
@SuppressLint("NewApi")
public static String requestData(String address, String params) {
System.out.println("params=" + params);
HttpURLConnection conn = null;
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
// ip host verify
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return urlHostName.equals(session.getPeerHost());
}
};
// set ip host verify
HttpsURLConnection.setDefaultHostnameVerifier(hv);
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL(address);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// POST
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
// set params ;post params
if (params != null) {
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(
conn.getOutputStream());
out.write(params.getBytes(Charset.forName("UTF-8")));
out.flush();
out.close();
}
conn.connect();
// 获取返回信息
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
try {
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(baos.toByteArray(), "UTF-8");
// String result = parsRtn(conn.getInputStream());
// return result;
} else {
System.out.println(conn.getResponseCode() + " "
+ conn.getResponseMessage());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.disconnect();
}
return null;
}
/**
* 这个是抽取出来的方法,返回请求的参数
*
* @param in
* @return
*/
public static String parsRtn(InputStream in) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
try {
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
in.close();
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new String(baos.toByteArray());
}
//在activity销毁时解绑
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//解绑
SMSSDK.unregisterEventHandler(eh);
}
//下面的不用管
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
接着布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="phone"
android:layout_weight="1"
android:padding="10dp"/>
<Button
android:id="@+id/bt_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="发送"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_code"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="phone"
android:layout_weight="1"
android:padding="10dp"/>
<Button
android:id="@+id/bt_check_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="验证"/>
</LinearLayout>
</LinearLayout>
最后注意要给权限:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 这个是sdk提供的一个界面的activity,现在不用!不过你可以用要在相应的MainActivity改变一下,
用sdk提供和自定义的代码已经写好测试过了 -->
<activity
android:name="com.mob.tools.MobUIShell"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:windowSoftInputMode="stateHidden|adjustResize" />
</application>
<!-- 所需的权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>