版权声明:转载请标注: https://blog.csdn.net/sinat_33381791/article/details/51112572
Android开发网络请求的工具类
最近项目中在做一个手机快捷登录模块的功能需求,需要向服务器来获取验证,然后进行快捷登录,所以本人写了一个关于网络请求的工具类来实现开发的需求,同时适用于如注册功能等需求,本人是一个新手如遇到错误或者是出现异常的请多多包涵,请大家多多指教。
NetworkUtils类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.gson.Gson;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
/**
* 网络请求工具类
*/
public class NetworkUtils {
private static Handler handler = new Handler();
/**
* 判断是否连接网络
* @param context
* @return
*/
public static boolean isConnectNet(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()
&& info.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
/**
* 发送一个POST请求,通过接口回调获取返回的数据
*
* @param url
* 请求的URL地址
* @param params
* 参数
* @return 服务器响应的字符串
*/
public static void sendPostRequest(final String url,
final HashMap<String, Object> params, final JsonCallBack callBack) {
//注意网络请求是一个耗时操作
new Thread(new Runnable() {
@Override
public void run() {
InputStream is = null;
OutputStream os = null;
ByteArrayOutputStream baos = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(
url).openConnection();
//设置请求方式POST
connection.setRequestMethod("POST");
//相应连接时长
connection.setConnectTimeout(10 * 1000);
// connection.setReadTimeout(10 * 1000);
if (params != null && !params.isEmpty()) {
// 获得输出流
os = connection.getOutputStream();
// 构建输出数据
byte[] data = encodeParams(params);
// 使用输出流向服务器写入数据
os.write(data);
}
// 读取服务器的响应
if (connection.getResponseCode() == 200) {
// 获取输入流
is = connection.getInputStream();
// 读取数据
baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[2048];
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
final byte[] result = baos.toByteArray();
//post方法
handler.post(new Runnable() {
@Override
public void run() {
//获取成功返回的数据
callBack.getData(result);
}
});
}else{
handler.post(new Runnable() {
@Override
public void run() {
//获取失败返回的数据
callBack.getDataFail(true);
}
});
}
} catch (SocketTimeoutException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.getDataFail(true);
}
});
Log.i("lll", "SocketTimeoutException失败"+e.getMessage());
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
Log.i("lll", "Exception失败"+e.getMessage());
e.printStackTrace();
} finally {
try {
//关闭
if (baos != null)
baos.close();
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* 网络请求参数编码,这里用Gson
*
* @param params
* @return
*/
public static byte[] encodeParams(HashMap<String, Object> params) {
if (params == null || params.isEmpty())
return new byte[0];
Gson gson = new Gson();
String json = gson.toJson(params);
System.out.println("获取的数据----->"+json);
return json.getBytes();
}
/**
* 发送get请求 通过接口回调返回的数据获取服务器的数据
*
* @param url
* @param callBack
*/
public static void sendGetRequest(final String url,
final JsonCallBack callBack) {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
InputStream is = null;
OutputStream os = null;
ByteArrayOutputStream baos = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(
url).openConnection();
connection.setRequestMethod("GET");
// 读取服务器的响应
if (connection.getResponseCode() == 200) {
// 获取输入流
is = connection.getInputStream();
// 读取数据
baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[2048];
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
final byte[] result = baos.toByteArray();
handler.post(new Runnable() {
@Override
public void run() {
callBack.getData(result);
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null)
baos.close();
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
*
*通过该静态代码块设置一个单例的接口回调
*/
static ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
public static void singleThread(final String url,
final JsonCallBack callBack){
final Handler handler = new Handler();
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
InputStream is = null;
OutputStream os = null;
ByteArrayOutputStream baos = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(
url).openConnection();
connection.setRequestMethod("GET");
// 读取服务器的响应
if (connection.getResponseCode() == 200) {
// 获取输入流
is = connection.getInputStream();
// 读取数据
baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[2048];
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
final byte[] result = baos.toByteArray();
handler.post(new Runnable() {
@Override
public void run() {
callBack.getData(result);
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null)
baos.close();
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
/**
*
*接口回调
*/
public interface JsonCallBack {
void getData(byte[] result);
void getDataFail(boolean fail);
}
}
ShortcutLoginActivity类
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.gaijiawang.constants.Constans;
import com.gaijiawang.kekecang.R;
import com.gaijiawang.kekecangactivity.BaseActivity;
import com.gaijiawang.utils.NetworkUtils;
import com.gaijiawang.utils.NetworkUtils.JsonCallBack;
import com.gaijiawang.utils.PhoneMatcherUtil;
import com.google.gson.JsonObject;
/**
*
* 手机号码快捷登录账号密码登录
*/
public class ShortcutLoginActivity extends BaseActivity implements
OnClickListener {
private EditText ed_phoneNum;// 手机号码
private EditText ed_yanzhengNum;// 输入验证码
private TextView tv_gainCaptcha_time;// 获取验证码+倒退时间
private Button btn_shortcut_login;// 登录
private String yanzhengNum;// 验证码
private String phoneNum;// 手机号码
private int FLAG_NUM;// 一个请求的标志
private TimeCount timeCount;
private static Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shortcut_login_activity);
//初始化
initView();
}
private void initView() {
ed_phoneNum = (EditText)findViewById(R.id.et_shoujihaoma);
ed_phoneNum = (EditText) findViewById(R.id.et_yanzhengma);
tv_gainCaptcha_time = (TextView) findViewById(R.id.tv_gainCaptcha_time);
tv_gainCaptcha_time.setOnClickListener(this);
btn_shortcut_login = (Button) findViewById(R.id.btn_shortcoutLogin);
btn_shortcut_login.setOnClickListener(this);
}
@Override
public void onClick(View v) {
phoneNum = ed_phoneNum.getText().toString().trim();// 手机号码
int id = v.getId();
switch (id) {
case R.id.tv_gainCaptcha_time:
// 获取验证码
getAuthNum();
break;
case R.id.btn_shortcoutLogin:
// 登录
shortcutLogin();
break;
}
}
/**
* 登录
*/
private void shortcutLogin() {
yanzhengNum = ed_yanzhengNum.getText().toString().trim();// 获取验证码
ed_phoneNum.setError(null);
ed_yanzhengNum.setError(null);
ed_phoneNum.clearFocus();
ed_yanzhengNum.clearFocus();
if (TextUtils.isEmpty(phoneNum)) {
ed_phoneNum.setError("手机号码不能为空!");
ed_phoneNum.requestFocus();
// Toast.makeText(this, "手机号码不能为空!", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(yanzhengNum)) {
ed_yanzhengNum.setError("验证码不能为空!");
ed_yanzhengNum.requestFocus();
return;
}
//向服务器中写入信息
putLoginMsg();
}
/**
* 向服务器中写入信息
*/
private void putLoginMsg() {
HashMap<String, Object>map = new HashMap<String, Object>();
map.put("phone", phoneNum);
map.put("code", yanzhengNum);
NetworkUtils.sendPostRequest(Constans.SHORTCUT_LOGIN_PATH, map, new JsonCallBack() {
@Override
public void getDataFail(boolean fail) {
// TODO Auto-generated method stub
}
@Override
public void getData(byte[] result) {
// TODO Auto-generated method stub
String json = new String(result);
try {
JSONObject jsonObject = new JSONObject(json);
int code = jsonObject.getInt("status");
if (code == 1) {
JSONObject jsonObject2 = new JSONObject("data");
int a=jsonObject2.getInt("");
String bString = jsonObject2.getString("msg");
//Constans.ACCESS_TOKEN
SharedPreferences sp = getSharedPreferences(Constans.ACCESS_TOKEN,Context.MODE_PRIVATE);
Editor edit = sp.edit();
//服务器获取的数据
//edit.putString("", value);
edit.commit();
}else{
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* 获取验证码
*/
private void getAuthNum() {
FLAG_NUM = 1;
ed_phoneNum.setError(null);
if (TextUtils.isEmpty(phoneNum)) {
ed_phoneNum.setError("手机号码不能为空!");
ed_phoneNum.requestFocus();
return;
// Toast.makeText(this, "手机号码不能为空!", Toast.LENGTH_LONG).show();
}
//PhoneMatcherUtil判断手机号码的正则判断
if (PhoneMatcherUtil.isMobileNo(phoneNum)) {
putPhoneNum();
} else {
ed_phoneNum.setError("亲,手机号码不对!");
ed_phoneNum.requestFocus();
// Toast.makeText(this, "亲,手机号码不对!", Toast.LENGTH_LONG).show();
ed_phoneNum.setText("");
}
// MD5加密算法得到Md5字符串
// String md5MobileString = MD5Util.MD5(mobileStr);
// parme.put("phone", md5MobileString);
}
/**
* 将手机号码post到服务器中获取验证码
*/
private void putPhoneNum() {
timeCount = new TimeCount(60000,10000);
timeCount.start();//启动倒计时
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("phone", phoneNum);
//Constans.GAIN_YANZHENGNUM_PATH服务器的url NetworkUtils.sendPostRequest(Constans.GAIN_YANZHENGNUM_PATH, map, new JsonCallBack() {
@Override
public void getDataFail(boolean fail) {
// TODO Auto-generated method stub
if (fail) {
Toast.makeText(ShortcutLoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
}
}
@Override
public void getData(byte[] result) {
// TODO Auto-generated method stub
String jsonString = new String(result);
try {
JSONObject jsonObject = new JSONObject(jsonString);
int status = jsonObject.getInt("status");
if (status==1) {
Toast.makeText(ShortcutLoginActivity.this,"获取成功", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(
ShortcutLoginActivity.this,
"获取验证码失败"
+ jsonObject
.getString("msg"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* 获取验证码计时
*/
public class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
// 参数依次为总时长,和计时的时间间隔
super(millisInFuture, countDownInterval);
}
// 计时完毕时触发
@Override
public void onFinish() {
tv_gainCaptcha_time.setText("重新获取");
tv_gainCaptcha_time.setClickable(true);
}
// 计时过程显示
@Override
public void onTick(long millisUntilFinished) {
tv_gainCaptcha_time.setClickable(false);
tv_gainCaptcha_time.setText(millisUntilFinished / 1000 + "s");
}
}
}
哈哈就是这样了,还有是xml文件
<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" >
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="短信验证" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp"
>
<EditText
android:id="@+id/et_shoujihaoma"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号码" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp"
>
<EditText
android:id="@+id/et_yanzhengma"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="验证码" />
<TextView
android:id="@+id/tv_gainCaptcha_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity="center"
android:text="获取验证码" />
</LinearLayout>
<Button
android:id="@+id/btn_shortcoutLogin"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="登录"
/>
</LinearLayout>