想要在安卓中使用HttpClient.jar包,记得不要用外部jar包,安卓自己有,如果用外部的话会产生错误。
想要用安卓本身的HttpClient.jar,需要做一下工作:
在app/bulid.gradle中添加如下配置:
android {
useLibrary'org.apache.http.legacy'
}
事先导入一个包(解析json数据):
compile'com.alibaba:fastjson:1.2.31'
package cn.a1949science.www.bookrecord.utils;
import java.security.MessageDigest;
/**
* 短信验证码验证类
* Created by 高子忠 on 2018/1/5.
*/
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' };
}
package cn.a1949science.www.bookrecord.utils;import com.alibaba.fastjson.JSON;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.ArrayList;import java.util.Date;/** * 短信工具类 * 验证验证码 * Created by 高子忠 on 2018/1/5. */public class MobileMessageCheck { private static final String SERVER_URL="https://api.netease.im/sms/verifycode.action";//请求的URL private static final String APP_KEY="0d24f47090a642edb13393c25d361f37";//账号 private static final String APP_SECRET="58d6f3ab4344";//密码 private static final String NONCE="123456";//随机数 public static String checkMsg(String phone,String sum) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(SERVER_URL); String curTime=String.valueOf((new Date().getTime()/1000L)); String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime); //设置请求的header post.addHeader("AppKey",APP_KEY); post.addHeader("Nonce",NONCE); post.addHeader("CurTime",curTime); post.addHeader("CheckSum",checkSum); post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); //设置请求参数 ArrayList nameValuePairs =new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("mobile",phone));
nameValuePairs.add(new BasicNameValuePair("code",sum));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
//执行请求
HttpResponse response=httpClient.execute(post);
String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
//判断是否发送成功,发送成功返回true
String code= JSON.parseObject(responseEntity).getString("code");
System.out.println(code);
if (code.equals("200")){
return "success";
}
return "error";
}
}
package cn.a1949science.www.bookrecord.utils;import com.alibaba.fastjson.JSON;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;/** * 短信工具类 * 发送验证码 * Created by 高子忠 on 2018/1/5. */public class MobileMessageSend { //发送验证码的请求路径URL private static final String SERVER_URL="https://api.netease.im/sms/sendcode.action"; private static final String APP_KEY="0d24f47090a642edb13393c25d361f37";//账号 private static final String APP_SECRET="58d6f3ab4344";//密码 private static final String MOULD_ID="4022146";//模板ID private static final String NONCE="123456";//随机数 //验证码长度,范围4~10,默认为4 private static final String CODELEN="6"; public static String sendMsg(String phone) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(SERVER_URL); String curTime=String.valueOf((new Date().getTime()/1000L)); String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime); //设置请求的header post.addHeader("AppKey",APP_KEY); post.addHeader("Nonce",NONCE); post.addHeader("CurTime",curTime); post.addHeader("CheckSum",checkSum); post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); //设置请求参数 List nameValuePairs =new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("mobile",phone));
nameValuePairs.add(new BasicNameValuePair("templateid",MOULD_ID));
nameValuePairs.add(new BasicNameValuePair("codeLen", CODELEN));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
//执行请求
HttpResponse response = httpClient.execute(post);
String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
//判断是否发送成功,发送成功返回true
String code= JSON.parseObject(responseEntity).getString("code");
if (code.equals("200"))
{
return "success";
}else{
return code;
}
}
}
package cn.a1949science.www.bookrecord.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Looper;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import cn.a1949science.www.bookrecord.R;
import cn.a1949science.www.bookrecord.utils.AMUtils;
import cn.a1949science.www.bookrecord.utils.MobileMessageCheck;
import cn.a1949science.www.bookrecord.utils.MobileMessageSend;
public class LoginActivity extends AppCompatActivity{
Context mContext = LoginActivity.this;
EditText phoneNumber,verification;
Button delete,getverification,loginButton;
MyCountTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
findView();
onClick();
}
//事件
private void onClick() {
//对输入的电话号码进行判断
phoneNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length() == 11) {
AMUtils.onInactive(mContext, phoneNumber);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//验证验证码是否正确
new Thread(){
@Override
public void run(){
String code = verification.getText().toString();
try {
String str = MobileMessageCheck.checkMsg(phoneNumber.getText().toString(), code);
if(str.equals("success")){
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
}else{
Looper.prepare();
Toast.makeText(mContext, "验证失败!", Toast.LENGTH_LONG).show();
Looper.loop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
getverification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = phoneNumber.getText().toString();
if(number.length()!=11)
{
Toast.makeText(mContext, "请输入11位有效号码", Toast.LENGTH_LONG).show();
return;
}
//如果输入的手机号不为空的话
if (!TextUtils.isEmpty(number)) {
timer = new MyCountTimer(60000, 1000);
timer.start();
//请求发送验证码
new Thread(){
@Override
public void run(){
try {
String number = phoneNumber.getText().toString();
String str = MobileMessageSend.sendMsg(number);
if (str.equals("success")) {
Looper.prepare();
Toast.makeText(mContext, "发送成功", Toast.LENGTH_SHORT).show();
Looper.loop();
} else {
Looper.prepare();
Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} else {
Toast.makeText(mContext, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
}
}
});
}
//寻找地址
private void findView() {
phoneNumber=(EditText)findViewById(R.id.phoneNumber);
verification=(EditText)findViewById(R.id.verification);
delete=(Button)findViewById(R.id.phoneNumberDelete);
getverification=(Button)findViewById(R.id.VerificationButton);
loginButton=(Button)findViewById(R.id.loginButton);
}
//按钮效果
private class MyCountTimer extends CountDownTimer {
MyCountTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
getverification.setEnabled(false);
getverification.setText((millisUntilFinished / 1000) +"秒后重发");
}
@Override
public void onFinish() {
getverification.setEnabled(true);
getverification.setText("重新发送验证码");
}
}
}