2013-01-23 30 views
0

我有一个问题,我想通过Android设备登录一个网站。我已经看过很多这方面的样本,但它不适合我。这是我的代码:http post数据登录不起作用?

DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.example.com/login.php"); 
    httppost.setHeader("Content-Type","text/html"); 
    ArrayList<BasicNameValuePair> pairs = new ArrayList(); 
    pairs.add(new BasicNameValuePair("username", "test1")); 
    pairs.add(new BasicNameValuePair("password", "pass1")); 
    try { 
     UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8); 

     /** Assign the POST data to the entity */ 
     httppost.setEntity(p_entity); 

     /** Perform the actual HTTP POST */ 
     HttpResponse response = httpclient.execute(httppost); 

     TextView txtView = (TextView)findViewById(R.id.txtMessage); 
     txtView.setText(EntityUtils.toString(response.getEntity())); 

    } catch (UnsupportedEncodingException uee) { 
     uee.printStackTrace(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } 

我不明白新的BasicNameValuePair(“username”,“test1”)。什么是attibute这里?

<input type="text" name="username" size="25" maxlength="40" value="" class="post" id="autofocus" tabindex="1"/> 

<input type="password" name="password" size="25" maxlength="32" class="post" tabindex="2"/> 

它只是返回登录页面。它不传递参数登录。有什么建议么 ?

回答

0

test1是您的用户名,pass1是您的密码。

如果你正在从edittexts的用户名和密码,然后使用此代码

pairs.add(new BasicNameValuePair("username", ed_user.getText().toString())); 
pairs.add(new BasicNameValuePair("password", ed_pass.getText().toString())); 

其中ed_usered_pass是你edittexts

+0

是的,但它不适合我。我尝试了很多次。但它只是返回登录页面。我想在登录后。它重定向到主页。但它总是返回login.php: - ? –

+0

如果你得到正确的结果,那么你需要移动到下一页使用[意向](http://www.mkyong.com/android/android-activity-from-one-screen-to-another-screen/) –

+0

不,我的意思是。它只是返回登录页面。它不传递数据登录。我不知道为什么会发生什么? –

0

检查HTML页面的源代码,并查找以下部分(例如):

<form name="frm" method="post" action="/cgi-bin/websms/index.pl" onSubmit="return validate()"> 

现在根据表单的action =“...”部分更新您的URL。