Send login with POST with Android!

2019-02-18 09:13发布

问题:

I have a login form in Android that I want to use to send a HttpPost request to a server and get a cookie back in return if the login was successful. I have one problem how do I implement a correct version of this and how do I get the cookie and store it on the device (do I store it in the preference database? so I can destroy it later on?).

I have this code right now:

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://a_site.com/logintest.aspx");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("txtUsername", "username"));
        nameValuePairs.add(new BasicNameValuePair("txtPassword", "123456"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        Log.v(TAG, "Response from server: " + response.toString());

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
}

How do I get the cookie and how do I store it if the login was successful?

回答1:

Rather than writing your own, you can do it the easy way:

inport org.apache.http.util.EntityUtils;
...
HttpResponse response = httpclient.execute(httppost);
String responseAsText = EntityUtils.toString(response.getEntity());


回答2:

The following code snippet will return a nicely formatted string representation of the http response:

public String responseHandler(HttpResponse response)
{
    HttpEntity resEntity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(
                    resEntity.getContent(), "UTF-8"));
            String line;
            String result = "";
            while (((line = br.readLine()) != null)) {              
                result = result + line + "\n";
            }

            return result;
}

How you choose to store the result is another question, I would suggest some sort of global variable.