Отобразить HttpResponse (строка из обработчика) в новом WebView - PullRequest
1 голос
/ 09 июня 2010

У меня есть следующий код в кнопке отправки формы 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) и начать новое действие, используя намерение, которое откроет веб-просмотр и загрузит HTML?

Ответы [ 3 ]

4 голосов
/ 09 июня 2010

Вы можете начать новое намерение с

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");

    }
}
0 голосов
/ 22 июня 2011

Если вы комбинируете свои замечательные методы, вы получаете что-то еще лучше, мой код требует только одного просмотра и работает с файлами cookie и сообщениями: 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

0 голосов
/ 11 июня 2010

Полученный код после применения вышеуказанного ответа выглядит следующим образом:

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

Полный код для базового класса веб-просмотра, который я использовал:

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>

Надеюсь, это поможет кому-то еще в будущем :) Благодаря неуважению.

...