android http发布回复到webview并导航

时间:2011-10-19 16:20:48

标签: android http-post webviewclient

我正在制作一个向Ilias服务器发帖请求的应用程序,我收到回复并在webview上打开它,我的问题是,如果我导航,当我点击某个链接时它不会保存我的凭据和teels me“你没有登录”并且不继续。

以下是代码:

public class ilias extends Activity {

 WebView webView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webView = (WebView)findViewById(R.id.webview);

        BufferedReader bufferedReader = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://www.ilias.de/docu/login.php?client_id=docu");
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("username", "stacked")); //this username 
        postParameters.add(new BasicNameValuePair("password", "overflow"));//works


  try {
   UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
         request.setEntity(entity);

         HttpResponse response= httpClient.execute(request);

   bufferedReader = new BufferedReader(
           new InputStreamReader(response.getEntity().getContent()));
   StringBuffer stringBuffer = new StringBuffer("");
   String line = "";
   String LineSeparator = System.getProperty("line.separator");
   while ((line = bufferedReader.readLine()) != null) {
    stringBuffer.append(line + LineSeparator); 
   }
   bufferedReader.close();

   Toast.makeText(ilias.this, 
     "Finished", 
     Toast.LENGTH_LONG).show();

   String webData = stringBuffer.toString();

   webView.loadData(webData,"text/html","UTF-8");
   webView.loadDataWithBaseURl("http://www.ilias.de/docu/",webData,"text/html","UTF-8","about:blank");

  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(ilias.this, 
     e.toString(), 
     Toast.LENGTH_LONG).show();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(ilias.this, 
     e.toString(), 
     Toast.LENGTH_LONG).show();
  }finally{
   if (bufferedReader != null){
    try {
     bufferedReader.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

    }
}

2 个答案:

答案 0 :(得分:0)

通过这种方式进行POST,你将失去存储cookie的能力。您还必须在WebView中模拟来自服务器的身份验证机制。您可以直接在WebView中使用带有请求正文的POST。您似乎通过URL编码实体传递用户名和密码,该实体可与WebView的post method兼容。

尝试类似:

String query = "username=" + username + "&password=" + password";
webview.postUrl("http://www.ilias.de/docu/login.php?client_id=docu", query.getBytes());

答案 1 :(得分:0)

如果您多次使用httppost,则可以通过httpclient维护cookie。如果您只是在网站中导航,那么网站实际上应该存储您的信息,因为它是由网站处理的内容,否则使httpclient成为公共静态全局并在整个活动或其他活动中共享它。