简体   繁体   中英

Android post request failed with OKHTTP

I am new to Android developing and I am trying to login https://m.colorado.edu/mycuinfo/ with OKHTTP3

Following are my codes

        OkHttpClient client = new OkHttpClient();

        HttpUrl url = HttpUrl.parse(urlString).newBuilder()
                .addQueryParameter("j_username", username)
                .addQueryParameter("j_password", password)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());

        } catch (IOException e){
            e.printStackTrace();
        }

The POST url is https://m.colorado.edu/mycuinfo/j_security_check

But the response is just the Source CODEs for the login page.

<form data-ajax="false" id="LoginForm" name="lForm" method="POST" action="j_security_check" autocomplete="off">
<p></p>
<b>CU Login Name:</b><br> <input tabindex="1" type="text" name="j_username" size="20" data-theme="c" />
<p></p>
<b>IdentiKey Password:</b><br> <input tabindex="2" type="password" name="j_password" size="20" data-theme="c" />
<p></p>
<button data-ajax="false" data-theme="a" value="Log in" tabindex="3">Login</button>
<p></p>

' Any thoughts?

I personally think it should be about session and cookies but I don't know how to do that with OKHTTP

I dont think you should try to do a POST request passing query parameters . QueryParameters are usually used for GET requests. Try to build a RequestBody and execute a request with it, like this:

RequestBody formBody = new FormEncodingBuilder()
    .add("j_username", username)
    .add("j_password", password)
    .build();
Request request = new Request.Builder()
    .url(urlString)
    .post(formBody)
    .build();

Response response = client.newCall(request).execute();

To add to Rafael Cardoso's comment, You definitely should not be using query parameters to log users in. That is considered a security risk. Using a RequestBody via a secured connection is preferable.

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