2013-11-02 28 views
0

我有sendPost()方法,它發送發佈數據以登錄到某個站點。我能夠獲得302的響應代碼。執行此方法後,我有一個sendPost2()方法,該方法在我成功登錄後可以工作。但是,我在sendPost2()中得到響應代碼200,它還告訴我沒有登錄。似乎在執行sendPost()後,httpclient將我註銷。你如何防止它註銷?發送發佈數據時HttpClient自動註銷

這裏是我的sendPost(),但我不能給你一個有效的用戶名和密碼:

private void sendPost() throws Exception { 

     String url = "http://sblive.auf.edu.ph/schoolbliz/commfile/login.jsp"; 

     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(url); 

     // add header 
     post.setHeader("User-Agent", USER_AGENT); 

     List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); 
     urlParameters.add(new BasicNameValuePair("user_id", "testusername")); 
     urlParameters.add(new BasicNameValuePair("password", "testpassword")); 
     urlParameters.add(new BasicNameValuePair("x", "47")); 
     urlParameters.add(new BasicNameValuePair("y", "1")); 
     urlParameters.add(new BasicNameValuePair("body_color", "#9FBFD0")); 
     urlParameters.add(new BasicNameValuePair("welcome_url", "../PARENTS_STUDENTS/main_files/login_success.htm")); 
     urlParameters.add(new BasicNameValuePair("login_type", "parent_student")); 

     post.setEntity(new UrlEncodedFormEntity(urlParameters)); 

     HttpResponse response = client.execute(post); 
     System.out.println("\nSending 'POST' request to URL : " + url); 
     System.out.println("Post parameters : " + post.getEntity()); 
     System.out.println("Response Code : " + 
            response.getStatusLine().getStatusCode()); 

     BufferedReader rd = new BufferedReader(
         new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer result = new StringBuffer(); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      result.append(line); 
     } 

     System.out.println(result.toString()); 
+0

當與網站的接口,因爲HTTP本身是無狀態協議,網站通常使用Cookie存儲會話數據。從您的代碼中,我沒有看到您發送網站希望您發送的Cookie的任何地方(Cookie關閉時瀏覽器的行爲)。由於每次請求都會發送空白cookie,因此自該POST響應初始以來,該網站假定您是完全獨立的客戶端。基本上,您必須重新發送網站期望您存儲的所有Cookie。 – initramfs

回答

0

配方

您需要cookie存儲以獲得地址keep the session ID between calls

代碼

HttpClient httpClient = new DefaultHttpClient(); 
CookieStore cookieStore = new BasicCookieStore(); 
HttpContext httpContext = new BasicHttpContext(); 
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
// ... 

HttpResponse response1 = httpClient.execute(method1, httpContext); 
// ... 

HttpResponse response2 = httpClient.execute(method2, httpContext); 
// ... 
+0

非常感謝你! :) – danieljohngomez