你好 Stackoverflowers!
我编写了一个相对简单的应用程序,由登录文本字段、密码文本字段和登录按钮组成。
我的目标是,当用户输入登录信息并触摸登录按钮时,应用程序会将用户登录到我指定的网站,并以不同的 Intent 或 WebView 打开它。我当前的实现使用 WebView 打开一个新 Activity 并传入登录信息。我的新 Activity 代码如下:
setContentView(R.layout.web);
try {
//add the users login information(username/pw) to a List
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5d4e414b40426f48424e4643014c4042" rel="noreferrer noopener nofollow">[email protected]</a>"));
nameValuePairs.add(new BasicNameValuePair("password", "password1"));
//declare a new HttpClient
HttpClient httpclient = new DefaultHttpClient();
//set the HttpPost to the desire URL
HttpPost httppost = new HttpPost(URL_STRING);
//set the entity to a new UrlEncodedForm with the login info and type
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//store the response
HttpResponse response = httpclient.execute(httppost);
//get the data from the response
String data = new BasicResponseHandler().handleResponse(response);
//get the webview from the xml
WebView webview = (WebView)findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
//load the return website from the server
webview.loadDataWithBaseURL(httppost.getURI().toString(), data, "text/html", HTTP.UTF_8, null);
这成功地让我登录到 URL(一个 https 站点)并打开页面,但是如果您尝试单击网站上的任何按钮,它会将您带回到 WebView 中的登录页面,并且确实如此不显示网站上的许多属性(图表/图形)。
这可能是 cookie 的事情吗?
那么有没有办法通过新 Intent 发送登录信息?或者我的 WebView 实现有解决方案吗?
(这是一个相对相似的问题,但从未得到明确的答案Android SSO (Single sign-on) for app)
感谢您的宝贵时间!非常感谢您能百忙之中查看我的问题。
编辑:所以giseks的解决方案对我有用,让网页保留在WebView中,但是页面上的图表/图形/等仍然没有显示,解决方案很简单为 WebSettings 启用 javascript
webview.getSettings().setJavaScriptEnabled(true);
这里是 Google 的 WebSettings Android API 供引用:WebSettings
这对我有帮助,希望对你也有帮助!
最佳答案
我的猜测是您的应用程序没有正确处理 cookie。看看这个问题,可能会有所帮助。
WebView and Cookies on Android
编辑
在您的代码中,您似乎只将从请求中检索到的 html 传递给 WebView。 cookies 似乎在某个地方丢失了。我建议您采用另一种方法。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webv = (WebView)findViewById(R.id.MainActivity_webview);
webv.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
String postData = FIELD_NAME_LOGIN + "=" + LOGIN +
"&" + FIELD_NAME_PASSWD + "=" + PASSWD;
// this line logs you in and you stay logged in
// I suppose it works this way because in this case WebView handles cookies itself
webv.postUrl(URL, EncodingUtils.getBytes(postData, "utf-8"));
}
关于android - 通过应用程序通过 HttpPost 登录网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11352697/