解决token 401问题

This commit is contained in:
huangzhuanghua
2016-11-16 14:22:07 +08:00
parent d74d91532b
commit b9eb8de88a
6 changed files with 131 additions and 99 deletions

View File

@ -275,14 +275,18 @@ public class FileUtils {
int statusCode = connection.getResponseCode();
Utils.log("statusCode = " + statusCode);
if (statusCode == HttpURLConnection.HTTP_OK) {
if (statusCode == 200) {
// {"icon":"http:\/\/gh-test-1.oss-cn-qingdao.aliyuncs.com\/pic\/57e4f4d58a3200042d29492f.jpg"}
JSONObject response = new JSONObject(b.toString().trim());
response.put("statusCode", HttpURLConnection.HTTP_OK);
response.put("statusCode", 200);
return response;
} else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
} else if (statusCode == 403) {
JSONObject response = new JSONObject(b.toString().trim());
response.put("statusCode", HttpURLConnection.HTTP_FORBIDDEN);
response.put("statusCode", 403);
return response;
} else if (statusCode == 401) {
JSONObject response = new JSONObject();
response.put("statusCode", 401);
return response;
}
} catch (Exception e) {

View File

@ -12,70 +12,77 @@ import com.gh.gamecenter.volley.extended.StringExtendedRequest;
/**
* Created by khy on 2016/11/9.
*
*/
public class PostCommentUtils {
public static void addCommentData(final String url, final String content, final Context context, final PostCommentListener listener) {
public static void addCommentData(final String url, final String content, final Context context,
final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
Utils.log("url::" + url, "/ content::" + content);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, url, content,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null){
listener.postSucced(response.toString());
listener.postSucced(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
TokenUtils.getToken(context, false);
addCommentData(url, content, context, listener);
return;
}
if (listener != null){
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN",TokenUtils.getToken(context));
request.addHeader("TOKEN", TokenUtils.getToken(context));
AppController.addToRequestQueue(request);
}
}).start();
}
public static void addCommentVoto(final String newsId, final Context context, final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, Config.COMMENT_HOST + "comment/" + newsId + "/vote" ,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("======onResponse", "onResponse");
if (listener != null){
listener.postSucced(response.toString());
listener.postSucced(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("======onErrorResponse", new String(error.networkResponse.data));
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
TokenUtils.getToken(context, false);
addCommentVoto(newsId, context, listener);
return;
}
if (listener != null){
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN",TokenUtils.getToken(context));
request.addHeader("TOKEN", TokenUtils.getToken(context));
AppController.addToRequestQueue(request);
}
}).start();
}
public interface PostCommentListener {
@ -83,5 +90,4 @@ public class PostCommentUtils {
void postFailed(VolleyError error);
}
}

View File

@ -9,7 +9,11 @@ import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.Response;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import com.tencent.stat.StatConfig;
import org.json.JSONException;
@ -66,7 +70,6 @@ public class TokenUtils {
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
// connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));
connection.connect();
@ -103,19 +106,24 @@ public class TokenUtils {
return null;
}
// 获取用户token
public static synchronized String getToken(Context context) {
//TODO 时间准确判断
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE,
Context.MODE_PRIVATE);
return getToken(context, true);
}
// 获取用户token
public static synchronized String getToken(Context context, boolean isCheck) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = System.currentTimeMillis();//TODO 用户有可能修改手机时间导致没能判断Token是否过期
// 判断token是否过期
if (time < expire) {
// token未过期
return token;
if (isCheck) {
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = Utils.getTime(context);
// 判断token是否过期
if (time < expire) {
// token未过期
return token;
}
}
}
@ -132,7 +140,6 @@ public class TokenUtils {
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
// connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));
connection.connect();
@ -160,6 +167,10 @@ public class TokenUtils {
editor.putString("token", jsonObject.getString("value"));
editor.putLong("token_expire", jsonObject.getLong("expire"));
editor.apply();
if (token != null && token.equals(jsonObject.getString("value"))) {
// 服务器返回的token和本地已存的token相同更新本地时间
getTime(context);
}
return jsonObject.getString("value");
} catch (JSONException e) {
e.printStackTrace();
@ -171,12 +182,36 @@ public class TokenUtils {
return null;
}
// 获取服务器时间
public static synchronized void getTime(Context context) {
final SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.GET, Config.HOST + "support/time/current",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.matches("^[0-9]{10}$")) {
try {
Editor editor = sp.edit();
editor.putLong("server_time", Long.parseLong(response));
editor.putLong("client_time", System.currentTimeMillis() / 1000);
editor.apply();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}, null);
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
public static synchronized void saveDeviceId(Context context, String device_id){
saveSharedPreferences(context, device_id);
saveDataFile(context, device_id);
svaeSDCard(device_id, "/gh-uuid");//SDCard根目录
svaeSDCard(device_id, "/system");//SDCard system目录
svaeSDCard(device_id, "/data");//SDCard data目录
svaeSDCard(device_id, "/gh-uuid");// SDCard根目录
svaeSDCard(device_id, "/system"); // SDCard system目录
svaeSDCard(device_id, "/data"); // SDCard data目录
}
//将uuid存到sp

View File

@ -78,26 +78,34 @@ public class CropImageActivity extends BaseActivity {
// 上传图片
JSONObject result = FileUtils.uploadFile(Config.USER_HOST + "icon",
path, TokenUtils.getToken(CropImageActivity.this));
dialog.dismiss();
if (result != null) {
try {
int statusCode = result.getInt("statusCode");
if (statusCode == HttpURLConnection.HTTP_OK) {
Intent data = new Intent();
data.putExtra("url", result.getString("icon"));
setResult(RESULT_OK, data);
finish();
handler.sendEmptyMessage(0);
} else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN
&& "too frequent".equals(result.getString("detail"))) {
handler.sendEmptyMessage(2);
}
} catch (JSONException e) {
e.printStackTrace();
try {
if (result != null && result.getInt("statusCode") == 401) {
result = FileUtils.uploadFile(Config.USER_HOST + "icon",
path, TokenUtils.getToken(CropImageActivity.this, false));
}
} else {
handler.sendEmptyMessage(1);
if (result != null) {
try {
int statusCode = result.getInt("statusCode");
if (statusCode == HttpURLConnection.HTTP_OK) {
Intent data = new Intent();
data.putExtra("url", result.getString("icon"));
setResult(RESULT_OK, data);
finish();
handler.sendEmptyMessage(0);
} else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN
&& "too frequent".equals(result.getString("detail"))) {
handler.sendEmptyMessage(2);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
handler.sendEmptyMessage(1);
}
} catch (JSONException e) {
e.printStackTrace();
}
dialog.dismiss();
} else {
dialog.dismiss();
handler.sendEmptyMessage(1);

View File

@ -27,6 +27,7 @@ import com.gh.common.constant.Config;
import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.TokenUtils;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadService;
import com.gh.gamecenter.db.info.FilterInfo;
@ -63,8 +64,6 @@ import de.greenrobot.event.EventBus;
*/
public class SplashScreenActivity extends BaseActivity {
public static final String TAG = SplashScreenActivity.class.getSimpleName();
private SharedPreferences sp;
private String from;
@ -226,7 +225,8 @@ public class SplashScreenActivity extends BaseActivity {
getUISetting();
getTime();
// 更新本地时间
TokenUtils.getTime(this);
/*
* 上传数据
@ -263,31 +263,6 @@ public class SplashScreenActivity extends BaseActivity {
}
}
/*
* 获取服务器时间
*/
private void getTime() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.GET, Config.HOST + "support/time/current",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.matches("^[0-9]{10}$")) {
try {
Editor editor = sp.edit();
editor.putLong("server_time", Long.parseLong(response));
editor.putLong("client_time", System.currentTimeMillis() / 1000);
editor.apply();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}, null);
request.setShouldCache(false);
AppController.addToRequestQueue(request, TAG);
}
/*
* 获取界面设置
*/
@ -313,7 +288,7 @@ public class SplashScreenActivity extends BaseActivity {
}
}
}, null);
AppController.addToRequestQueue(request, TAG);
AppController.addToRequestQueue(request);
}
/*
@ -346,7 +321,7 @@ public class SplashScreenActivity extends BaseActivity {
}
}
}, null);
AppController.addToRequestQueue(request, TAG);
AppController.addToRequestQueue(request);
}
/*
@ -400,7 +375,7 @@ public class SplashScreenActivity extends BaseActivity {
}
}
}, null);
AppController.addToRequestQueue(request, TAG);
AppController.addToRequestQueue(request);
}
// 跳转到主界面

View File

@ -425,25 +425,29 @@ public class PersonalFragment extends Fragment implements View.OnClickListener,
@Override
public void onErrorResponse(VolleyError error) {
waitDialog.dismiss();
if (error.networkResponse != null
&& error.networkResponse.statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
try {
JSONObject response = new JSONObject(new String(error.networkResponse.data));
String detail = response.getString("detail");
if ("too long".equals(detail)) {
Toast.makeText(getActivity(), "昵称太长", Toast.LENGTH_SHORT).show();
} else if ("invalid".equals(detail)) {
Toast.makeText(getActivity(), "非法字符", Toast.LENGTH_SHORT).show();
} else if ("repeat".equals(detail)) {
Toast.makeText(getActivity(), "昵称已存在", Toast.LENGTH_SHORT).show();
} else if ("no change".equals(detail)) {
Toast.makeText(getActivity(), "昵称一致", Toast.LENGTH_SHORT).show();
} else if ("too frequent".equals(detail)) {
Toast.makeText(getActivity(), "修改太频繁,请稍后再试", Toast.LENGTH_SHORT).show();
if (error.networkResponse != null) {
if (error.networkResponse.statusCode == 401) {
TokenUtils.getToken(getActivity(), false);
modifyNickname(nickname);
} else if (error.networkResponse.statusCode == 403) {
try {
JSONObject response = new JSONObject(new String(error.networkResponse.data));
String detail = response.getString("detail");
if ("too long".equals(detail)) {
Toast.makeText(getActivity(), "昵称太长", Toast.LENGTH_SHORT).show();
} else if ("invalid".equals(detail)) {
Toast.makeText(getActivity(), "非法字符", Toast.LENGTH_SHORT).show();
} else if ("repeat".equals(detail)) {
Toast.makeText(getActivity(), "昵称已存在", Toast.LENGTH_SHORT).show();
} else if ("no change".equals(detail)) {
Toast.makeText(getActivity(), "昵称一致", Toast.LENGTH_SHORT).show();
} else if ("too frequent".equals(detail)) {
Toast.makeText(getActivity(), "修改太频繁,请稍后再试", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();