【问题标题】:Keep session open from Android app to website in a webview在 web 视图中保持从 Android 应用程序到网站的会话打开
【发布时间】:2012-03-03 04:07:13
【问题描述】:

我有一个正在创建的 android 应用程序,并且我有一个登录页面作为第一个意图。然后这将打开一个选项卡并将用户带到第一个选项卡,该选项卡会显示一个 web 视图。网站是应用程序的重要组成部分,需要用户登录。网站和应用程序使用在同一台服务器上运行的相同登录脚本,因此登录信息相同。我想使用登录到 webview 内的应用程序时创建的会话,这样当用户进入 webview 时,他们仍然登录。我尝试使用共享首选项重新登录 webview,但这不是在职的。我能够将共享首选项传递给它,但它仍然告诉我我没有在网站上登录。对此主题的任何帮助将不胜感激。

这是我的代码:

用于创建我将在所有类之间传递的 defaultHttpRequest 的连接类。

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class Connection1 {


    public static HttpClient httpclient = new DefaultHttpClient();
    private static HttpPost httpPost;

    public Connection1(){
    }

    public HttpPost getHttpPost(){
        return httpPost;
    }
    public HttpResponse getResponse() throws ClientProtocolException, IOException{
        return httpclient.execute(httpPost);
    }
    public void setEntity(UrlEncodedFormEntity entity){
        httpPost.setEntity(entity);
    }
    public void setHttpPost(String script){
        httpPost = new HttpPost(script);
    }
}

将显示网站页面的 Webapp 类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebApp extends Activity {

    public static final String PREFS_NAME = "myPrefsFile";
    private static final String PREFS_USERNAME = "username";
    private static final String PREFS_PASSWORD = "password";

    String username = "";
    String password = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        setContentView(R.layout.webapp);
        SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        username = pref.getString(PREFS_USERNAME, null);
        password = pref.getString(PREFS_PASSWORD, null);
        System.out.println(username + "-" + password);
        postLoginData();


    }

    public void postLoginData() {

        // Create a new HttpClient and Post Header
        Connection1 connection = new Connection1();
        connection
                .setHttpPost("script.php");

        try {

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

            String str = inputStreamToString(
                    connection.getResponse().getEntity().getContent())
                    .toString();

            if (str.toString().equalsIgnoreCase("success")) {
                WebView webapp = (WebView) findViewById(R.id.webView1);  
                webapp.loadUrl("URL");
                webapp.setWebViewClient(new WebViewClient());
                webapp.getSettings().setJavaScriptEnabled(true);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Return full string
        return total;
    }
}

【问题讨论】:

    标签: android android-webview


    【解决方案1】:

    在您的 WebView 实例上,调用它。

    webView.setHttpAuthUsernamePassword(url,"", "@"+username, password);
    

    并覆盖以下方法:

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url+"?name="+username+"&password="+password);
        view.loadUrl(url);
        return true;
    }
    

    【讨论】:

    • 对不起,如果这很烦人,但我对 java 很陌生,我在实现这个时遇到了麻烦。你会把它放在我提供的代码中的什么地方?
    【解决方案2】:
    webView = (WebView) findViewById(R.id.webview);
    webView.clearCache(true);
    WebViewDatabase.getInstance(this).clearHttpAuthUsernamePassword(); 
    webView.setWebViewClient(new PasswordWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    
    public class PasswordWebViewClient extends WebViewClient {
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //view.loadUrl(url+"?name="+username+"&password="+password);
            view.loadUrl(url);
    
            //webView.loadUrl("https://www.google.com/accounts/ServiceLoginAuth? continue=http://mail.google.com/gmail&service=mail&Email=username&Passwd=password&null=Sign+in");
    
            return true;
        }
    
        public void onReceivedHttpAuthRequest (WebView view,
             HttpAuthHandler handler, String host, String realm){
             System.out.println("Entered into onReceivedHttpAuthRequest");
    
             handler.proceed(username, password);
        }
    
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
             Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
        }
    
    }
    

    【讨论】:

    • 也许我是个白痴,但我似乎无法让您的任何一个答案起作用。感谢您试图通过回答问题来帮助我,但没有人向我提供足够的信息来解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    相关资源
    最近更新 更多