简体   繁体   中英

HTTP Post Request over a Login Application

I am not able to send HTTP Post request. I am developing a login application where it should login from a post method API link using appropriate credentials. Once it logins, next activity should show other information present in the API(JSON).

Can anyone please guide me to do this by sending any references or explain with a sample code.

You can login using following code. This uses AsyncTask since android won't allow you to use Main Thread for networking stuff. However be cautious using Async Task . These are a good way to leak memory. Also you can always use Firebase Auth API to facilitate login, which are more secure, more easy, don't have to worry about server side programming and require very less code on your side.

public class RegistryHelper extends AsyncTask<String, Void, String> {
public static final String link = "http://www.yourlink.com/login.php";
public String data = null;

public RegistryHelper() {
}

@Override
protected void onPreExecute() {
}

@Override
protected String doInBackground(String... params) {
    try {
        URL url = new URL(link);
        data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8") + "&"
                + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(20000);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
        BufferedReader read = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = read.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }
}

@Override
protected void onPostExecute(String result) {
    if (result.equals("LOGIN_SUCCESS")) {
        //Your action
    } else {
        //Your else action
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM