2013-10-19 112 views
0

我想在android中創建一個webview訪問到一個網站,我做了一些代碼,從用戶名和密碼從網站獲取cookie。我得到的結果是:使用Cookie訪問一個網站

[version: 0][name: MoodleSession][value: arkitgq9pabpnjka5l0qbj75u1][domain: 192.168.1.105][path: /moodle/][expiry: null] 

現在我不知道如何使用它來登錄到網站。請幫幫我。 謝謝。

回答

0

它非常簡單。

簡答

這裏的代碼片段,做這個任務:

當我們從登陸頁面1日迴應,我們存儲cookie通過這種方式:

List<Cookie> mCookies = null; 

... 

mCookies = httpclient.getCookieStore().getCookies(); 

下一頁登錄時,我們創建CookieStore

CookieStore cookieStore = new BasicCookieStore(); 

和存儲我們的餅乾:

for(Cookie cook : mCookies){ 
    cookieStore.addCookie(cook); 
} 

後,店內提供在HTTP客戶端:

httpclient.setCookieStore(cookieStore); 

這就是全部。

UNITEST如果你有興趣,連接到圈養門戶網站登錄

其工作代碼,以防萬一,看看它是如何工作

private static String URL = ""; 
    List<Cookie> mCookies = null; 
    String mHost = null; 



    @Override 
    public void setUp() throws Exception{ 
     super.setUp(); 


     MessageItf imp = this; 
     LoggerImp.implMessge(imp); 

     mContext = getContext(); 

     assertNotNull(mContext); 

     URL = mContext.getString(R.string.URL); 

    } 



    @Override 
    protected void tearDown() throws Exception { 
     super.tearDown();    
    } 



    public void redirect(String url){ 

     StringBuilder buff = new StringBuilder(); 

     DefaultHttpClient httpclient = null; 
     //  boolean success = false; 

     try {   
      Log.d("test_runner","send Data started"); 


      HttpParams params = new BasicHttpParams(); 
      int m_timeout = 60000; 
      ConnManagerParams.setTimeout(params, m_timeout);    
      HttpConnectionParams.setStaleCheckingEnabled(params, false); 
      HttpConnectionParams.setSocketBufferSize(params, 8192); 

      HttpConnectionParams.setConnectionTimeout(params, m_timeout); // connection timeout 
      HttpConnectionParams.setSoTimeout(params, m_timeout);   // socket timeout 


      httpclient = new DefaultHttpClient(params); 

      HttpGet httpget = new HttpGet(url); 

      HttpContext context = new BasicHttpContext(); 
      HttpResponse response = httpclient.execute(httpget, context); 


      mCookies = httpclient.getCookieStore().getCookies(); 

      if (mCookies.isEmpty()) { 
       Log.d("test_runner", "Cookies: None"); 
      } else { 
       for (int i = 0; i < mCookies.size(); i++) { 
        System.out.println("- " + mCookies.get(i).toString()); 
        Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString()); 
       } 
      } 

      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode != HttpStatus.SC_OK) { 
       Header[] headers = response.getHeaders("Location"); 

       if (headers != null && headers.length != 0) { 
        String newUrl = headers[headers.length - 1].getValue(); 

        redirect(newUrl);     

       } 
      } 
      else{ // status 200 

       HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); 

       mHost = currentHost.toURI(); 

       HttpEntity entity = response.getEntity(); 

       if (entity != null) { 


        InputStream is = entity.getContent(); 
        InputStreamReader isr = new InputStreamReader(is); 
        BufferedReader br = new BufferedReader(isr, 1024 * 4); 
        String line = null; 
        while ((line = br.readLine()) != null) { 
         //System.out.println("Data Sender: " + line); 

         buff.append(line).append("\n"); 

        } 
        is.close(); 

       } else { 
        Log.d("test_runner", "Data Sender: response is null"); 
       } 

       Log.d("test_runner", "Output: " + buff); 


      } 
     } catch (Exception e) { 
      Log.e("test_runner", ThrowableToString.fromThrowableToString(e)); 
     } 

     if (httpclient != null) {   
      httpclient.getConnectionManager().shutdown(); 
     }  

    } 


    public void test_runner(){ 
     String url = "http://google.com"; 

     redirect(url);  
    } 




    private void doPost(String formAction, String inputRootValue, 
      String inputRootName, String onSubmitName, String onSubmitVal) { 

     StringBuilder buff = new StringBuilder(); 

     DefaultHttpClient httpclient = null; 

     try { 

      HttpParams params = new BasicHttpParams(); 
      int m_timeout = 60000; 
      ConnManagerParams.setTimeout(params, m_timeout);    
      HttpConnectionParams.setStaleCheckingEnabled(params, false); 
      HttpConnectionParams.setSocketBufferSize(params, 8192); 

      HttpConnectionParams.setConnectionTimeout(params, m_timeout); // connection timeout 
      HttpConnectionParams.setSoTimeout(params, m_timeout);   // socket timeout 

      CookieStore cookieStore = new BasicCookieStore(); 

      for(Cookie cook : mCookies){ 
       cookieStore.addCookie(cook); 
      } 

      httpclient = new DefaultHttpClient(params); 
      httpclient.setCookieStore(cookieStore); 

      if(mHost != null){ 
       formAction = mHost + "/www/" + formAction; 
      } 
      else{ 
       formAction = "http://localhost.ap.coova.org/www/" + formAction; 
      } 




      HttpPost httpost = new HttpPost(formAction); 

      List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
      nvps.add(new BasicNameValuePair(inputRootName, inputRootValue)); 
      nvps.add(new BasicNameValuePair(onSubmitName, onSubmitVal)); 


      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 




      HttpResponse response = httpclient.execute(httpost); 

      HttpEntity entity = response.getEntity(); 

      if (entity != null) { 

       StatusLine statusLine = response.getStatusLine(); 
       int statusCode = statusLine.getStatusCode(); 

       if(statusCode != 200){ 

       } 

       Log.d("test_runner", "response.getStatusLine: " + response.getStatusLine()); 

       InputStream is = entity.getContent(); 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader br = new BufferedReader(isr); 
       String line = null; 
       while ((line = br.readLine()) != null) { 
        //System.out.println("Data Sender: " + line); 

        buff.append(line).append("\n"); 


       } 
       is.close(); 

       //entity.consumeContent(); 
      } else { 

      } 

      Log.d("test_runner", "response: " + buff.toString()); 


     } catch (Exception e) { 
      Log.e("test_runner", ThrowableToString.fromThrowableToString(e)); 
     } 

     if (httpclient != null) { 
      // resource cleanup 
      httpclient.getConnectionManager().shutdown(); 
     } 

    } 
+0

代碼真正幫助我,非常感謝你,我只想再問一個問題,我們如何使用這個cookie通過jsoup connect來獲取網站上的文檔類型? –

+0

歡迎您。如果你發現我的答案有幫助,請投票,關於你的問題,我從來沒有這樣做,所以不能回答,但嘗試看到這個帖子:http://stackoverflow.com/questions/10518972/open-a-connection-with-jsoup -get狀態碼,和解析文檔/ 10519976#10519976 –

相關問題