2014-01-29 37 views
1

我想檢索該被保護和被重定向到登錄頁面每次正試圖得到一個受保護的資源的服務器JSON的信息。所以我應該使用cookie來實現對信息的訪問。Android的 - 在HttpContext的餅乾不會檢索不止一次每個URL

不幸的是POST每個URL(共3個),我有,只是工作一次。

要登錄該應用程序是使用下面的功能提出:

// Making HTTP request 
    try { 
     httpClient = getNewHttpClient(); 

     String redirectedUrl = getUrl(url); 

     // defaultHttpClient 
     HttpPost httpPost = new HttpPost(redirectedUrl); 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("username", login)); 
     nameValuePairs.add(new BasicNameValuePair("password", password)); 

     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     httpContext = new BasicHttpContext(); 
     CookieStore mCookieStore  = new BasicCookieStore();   
     httpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); 

     HttpResponse response = httpClient.execute(httpPost, httpContext); 

     HttpEntity entity = response.getEntity(); 

     String html = null; 
     if (entity != null) { 
      InputStream instream = entity.getContent(); 
      try { 
       html = streamToString(instream); 
      } finally { 
       instream.close(); 
      } 
     } 

     if ((html != null) && html.contains("error loginError")) { 

     } else 
      return html; 
    } catch (IOException e) { 

} 

並在日誌中,我試圖讓以同樣的方式的信息,但它只是每個URL工作一次之後。我不知道爲什麼,下面是我如何試圖在登錄後獲取信息。

 HttpPost httpPost = new HttpPost(url); 

     HttpResponse response = httpClient.execute(httpPost, httpContext); 

     HttpEntity entity = response.getEntity(); 
     String html = null; 
     if (entity != null) { 
      InputStream instream = entity.getContent(); 
      try { 
       html = streamToString(instream); 
      } finally { 
       instream.close(); 
      } 
     } 

當我試圖讓IOException就會被倒掉的信息第二次,HttpClient的的HttpContext都是全局和靜態。

回答

0

我得到了一個解決方案,我不認爲這是一個很好的解決方案,但它工作在所有。

爲了使其停止得到IOException異常,所有的崗位,這意味着對於所有帖子我要設置一個新的HttpContext記錄和有效之前,我只是做了到登錄函數的調用。

如果有人有更好的解決辦法,我會很高興聽到你的心聲。

PS:其實這個問題是關於服務器端的會話持續時間,現在它的正常工作,反正我會在這裏讓話題,因爲可能是正在實施這種解決方案某人有用。