【问题标题】:Display HttpResponse (string from Handler) in new WebView在新的 WebView 中显示 HttpResponse(来自 Handler 的字符串)
【发布时间】:2010-06-09 16:18:21
【问题描述】:

我在表单的提交按钮 onClickListener 中有以下代码:

String action, user, pwd, user_field, pwd_field;

        action = "theURL";

        user_field = "id";
        pwd_field = "pw";
        user = "username";
        pwd = "password!!";

        List<NameValuePair> myList = new ArrayList<NameValuePair>();
        myList.add(new BasicNameValuePair(user_field, user)); 
        myList.add(new BasicNameValuePair(pwd_field, pwd));

        HttpParams params = new BasicHttpParams();
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(action);
        HttpResponse end = null;
        String endResult = null;

        try {
            post.setEntity(new UrlEncodedFormEntity(myList));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        try {
            HttpResponse response = client.execute(post);
            end = response;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  


        BasicResponseHandler myHandler = new BasicResponseHandler();

        try {
            endResult = myHandler.handleResponse(end);
        } catch (HttpResponseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

如何获取结果字符串 (endResult) 并使用将打开 webview 并加载 html 的意图启动新活动?

【问题讨论】:

    标签: android webview android-intent httpresponse


    【解决方案1】:

    你可以用

    开始一个新的意图
    Intent myWebViewIntent = new Intent(context, MyWebViewActivity.class);
    myWebViewIntent.putExtra('htmlString', endResult);
    context.startActivity(myWebViewIntent);
    

    然后在您的 MyWebViewActivity 类中,您将拥有如下内容:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.my_view_that_contains_a_webview);
        WebView webview = (WebView)findViewById(R.id.my_webview);
    
        Bundle extras = getIntent().getExtras();
        if(extras != null) {
    
             // Get endResult
             String htmlString = extras.getString('htmlString', '');
             webview.loadData(htmlString, "text/html", "utf-8");
    
        }
    }
    

    【讨论】:

    • 这正是我想要的,谢谢!问题:上下文指的是什么? (我是新手)新类需要扩展什么类型的活动?不确定它是否重要,但它不允许在 htmlstring 周围加上单引号最后,extras.getstring 不接受 2 个字符串参数,只有一个?
    • 回答我自己的问题:上下文需要设置为 NameOfMainAppClass.this。第二个类(带有 webview 的类)仅扩展了 Activity。单引号/双引号无关紧要,将第二个参数留给 getString() 不会影响结果。虽然,正如我在另一篇 StackOverflow 帖子中发现的那样,loadData() 不能很好地用于直接 html,但使用完整方法 loadDataWithBaseURL() 时我得到了更好的结果。
    • 酷,很高兴你把它整理好了!
    • 不幸的是,我现在面临一个新问题......当我点击第一页的链接时,webview 似乎没有保留登录信息。
    • 我认为这是因为当您单击另一个链接时,它会打开默认浏览器而不是在 webview 中,但我通过实现 webviewclient 解决了这个问题,它仍然会丢失会话信息。有什么想法吗?
    【解决方案2】:

    应用上述答案后得到的代码如下:

    Intent myWebViewIntent = new Intent(YourAppClassHere.this, YourWebViewClassHere.class);
    myWebViewIntent.putExtra("htmlString", theStringThatHoldsTheHTML);
    startActivity(myWebViewIntent);
    

    我使用的基本 webview 类的完整代码是:

    public class MyWebView extends android.app.Activity{
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
    
        WebView webview = (WebView)findViewById(R.id.mainwebview);
    
        Bundle extras = getIntent().getExtras();
        if(extras != null) {
    
             // Get endResult
             String htmlString = extras.getString("htmlString");
             webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
        }
    
       }
    }
    

    同样值得注意的是,无论如何,这对我来说每次都会使程序崩溃,直到我在 AndroidManifest.xml 中添加以下行:

    <activity android:name=".MyWebView">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    

    希望这会在未来帮助其他人:) 感谢 disretrospect。

    【讨论】:

    • 它确实...... 2 年后:) 谢谢大家! 4 周来一直在寻找这个解决方案,也许更多..
    【解决方案3】:

    如果你结合你的好方法,你会得到更好的东西,我的代码只需要一个视图,并且可以使用 cookie 和 post vars :D

        private static final int TIMEOUT_MS = 3000;
        private WebView mWebView;
        private static final String redirURL = "http://www.somelogin.com/havefun.php";
    
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
    
            //------------------ COOKIES -----------------------//
            CookieSyncManager.createInstance(this); 
            CookieManager cookieManager = CookieManager.getInstance(); 
            Date dateObj = new Date();
    
            dateObj.setTime(dateObj.getTime() + 2 * 7 * 24 * 60 * 60 * 1000);
            String sA = "acc=" + 0;
            String sL = "lgn=";
            SimpleDateFormat postFormater = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz"); 
            String oD = postFormater.format(dateObj);   
            String cookieString = "logondata=" + sA + "&" + sL + "; expires="+ oD; 
            cookieManager.setCookie(redirURL, cookieString); 
            CookieSyncManager.getInstance().sync(); 
    
    
    
            //------------------ WEBVIEW -----------------------//
            mWebView = (WebView) findViewById(R.id.webview);
    
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setSavePassword(true);
            webSettings.setSaveFormData(true);
            webSettings.setJavaScriptEnabled(true);
            webSettings.setSupportZoom(false);
    
            mWebView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url){
                    // do your handling codes here, which url is the requested url
                    // probably you need to open that url rather than redirect:
                    view.loadUrl(url);
                    return false; // then it is not handled by default action
               }
    
            });
    
            //------------------------------ HTTP 4.0 REDIRECT --------------------------//
    
            HttpClient httpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
            HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
            HttpPost httpPost = new HttpPost(redirURL);  
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("curl", "varl"));  
            nameValuePairs.add(new BasicNameValuePair("flags", "0")); 
            nameValuePairs.add(new BasicNameValuePair("forcedownlevel", "0"));    
            nameValuePairs.add(new BasicNameValuePair("formdir", "9"));
            nameValuePairs.add(new BasicNameValuePair("username", "Tijs"));  
            nameValuePairs.add(new BasicNameValuePair("password", "mwhahah"));  
            nameValuePairs.add(new BasicNameValuePair("trusted", "1"));
            HttpResponse end = null;
            String endResult = null;
    
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpClient.execute(httpPost);
                end = response;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
    
            BasicResponseHandler myHandler = new BasicResponseHandler();
    
            try {
                endResult = myHandler.handleResponse(end);
            } catch (HttpResponseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            mWebView.loadData(endResult, "text/html", "utf-8");
    

    希望你喜欢这个代码:P

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 2013-04-23
      相关资源
      最近更新 更多