你好我想问个问题
我想使应用程序与我创建的web服务相连接
我的应用程序有两个唯一的ID,称为app_id和令牌,app_id在应用程序首次启动时仅生成一次,令牌由Web服务生成
每次请求,我都必须检查令牌是否已过期,如果令牌已过期,它将调用单独的web服务并生成新的令牌
问题是应用程序必须访问两个不同的Web服务:请求新令牌并获取另一个所需数据
我使用asynctask,但是web服务对请求令牌的响应总是相同的,我不知道为什么
protected Boolean doInBackground(Void... params) {
int status = 0;
int token_expired=0;
String token_val = token.getToken(getBaseContext());
for(int i=0;i<5 && status==0;i++) {
try {
Thread.sleep(1000);
//function to check if token already expired or not and request new token using http post
token_expired = token.checkToken(getBaseContext());
System.out.println("token expired: " +token_expired);
if (token_expired==1 || token_expired==2) {
//function to call another web service and get a data from it
status = rclient.Execute("POST");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (status==0) {
return false;
}else{
return true;
}
}
谢谢你!
最佳答案
哦,是的,这是来自类令牌处理程序的check token函数
public Integer checkToken(Context context) {
int status = 0; //0 = failed to request token , 1 = successfully request new token, 2 = token has not expired yet
String token_id = getToken(context);
System.out.println("token_id: " +token_id);
//if (token_id!=null) {
Long time = getTime(context);
Long curr_time = System.currentTimeMillis()/1000;
System.out.println("time before: " +time);
System.out.println("time current: " +curr_time);
Long interval = curr_time - time;
System.out.println("interval: " +interval);
if (interval>10) {
status = TokenGenerator(context);
}else {
status = 2;
}
//}
return status;
}
}
这是一个从同一个类请求新令牌的函数
public synchronized Integer TokenGenerator(Context context) {
int status = 0;
SharedPreferences sharedPrefs = context.getSharedPreferences(TOKEN_STORAGE, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
try {
rclient.AddJSON("app_id", uniqueID);
rclient.CompileJSON();
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
status = rclient.Execute("POST");
} catch (Exception e) {
e.printStackTrace();
}
if (status==1) {
String response = rclient.getResponse();
String token = null;
System.out.println("uuid_response: " +response);
try {
JSONObject json = new JSONObject(response);
token = json.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
System.out.println("time: " +ts);
Editor editor = sharedPrefs.edit();
editor.putString(TIMESTAMP, ts);
editor.putString(TOKEN_ID, token);
editor.commit();
}
return status;
}
因此,基本上rest客户机类调用了两次,第一次是在类令牌处理程序中请求新的令牌,第二次是从活动本身调用
关于java - 在Android中发布多个http帖子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15965164/