我正在開發一個Android項目,我正在通過線程的問題,我正在做一個HTTP請求。如何等待最後一個線程再去之前
我試圖從API獲取令牌刷新令牌...。
下面是代碼:
public class OAuthHelper {
static TokenModel tokenObj;
final static CountDownLatch latch = new CountDownLatch(1);
public static TokenModel getTokens(final RequestModel request) throws InterruptedException{
Thread thread = new Thread()
{
@Override
public void run()
{
try
{
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.listopresto.com/oauth/token");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (request.getType() == "password"){
Log.i("infos", "password");
nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
nameValuePairs.add(new BasicNameValuePair("client_id", "antoine"));
nameValuePairs.add(new BasicNameValuePair("client_secret", "toto"));
nameValuePairs.add(new BasicNameValuePair("username", "[email protected]"));
nameValuePairs.add(new BasicNameValuePair("password", "toto"));
}
else{
Log.i("infos", "refresh_token");
nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
nameValuePairs.add(new BasicNameValuePair("client_id", "antoine"));
nameValuePairs.add(new BasicNameValuePair("client_secret", "toto"));
nameValuePairs.add(new Bas icNameValuePair("refresh_token", request.getRefreshToken()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String s = reader.readLine();
Gson gson = new Gson();
tokenObj = gson.fromJson(s, new TypeToken<TokenModel>(){}.getType());
latch.countDown();
} catch (ClientProtocolException e) {
Log.i("infos", "first");
} catch (IOException e) {
Log.i("infos", "second");
}
}
catch (Exception e){
Log.i("infos", "third");
}
}
};
thread.start();
latch.await();
return (tokenObj);
}
}
當我做一弗朗用戶名和密碼的請求是沒有問題的。我用令牌得到正確的對象...但是當我做第二個時,看起來我在線程結束之前返回tokenObj。我認爲我通過使用latch.await()解決了這個問題,但我仍然有問題。
我正在尋找一種解決方案,在返回tokenObj之前等待線程結束。
謝謝!