使用cookie访问网站

时间:2013-10-19 08:28:44

标签: android cookies

我正在尝试在android中创建一个webview来访问一个网站,我做了一些代码,通过用户名和密码从网站上获取cookie。我得到的结果是:

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

现在我不知道如何使用它登录网站。请帮我。 感谢。

1 个答案:

答案 0 :(得分:0)

非常简单。

简答

以下是执行此任务的代码片段:

当我们从登录页面获得第一个回复时,我们通过这种方式存储Cookie:

List<Cookie> mCookies = null;

 ...

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

下次登录时,我们会创建CookieStore

 CookieStore cookieStore = new BasicCookieStore(); 

并存储我们的Cookie:

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();
        }

    }