Ahmed Mustafa
Ahmed Mustafa

Reputation: 139

Python Requests to Java OkHttp for Android

I have the following code working perfectly in Python:

login_data = {'identifier': '[email protected]', 'password': 'Password'}

url = "https://www.duolingo.com/2017-06-30/login?fields="
p = requests.post(url, data = json.dumps(login_data))

if p.status_code is 200:
    print("SUCCESS")
else:
    print("ERROR")

I want to convert it to Java using OkHttp to be able to implement it in Android Studio. I have written the following code but it gives Status Code: 422 which according to Google means Unprocessable Entity:

OkHttpClient client = new OkHttpClient();

String url = "https://www.duolingo.com/2017-06-30/login?fields=";
String login_data = "{\"identifier\": \"[email protected]\", \"password\": \"Password\"";
RequestBody body = RequestBody.create(login_data, MediaType.parse("application/json"));

    Request postRequest = new Request.Builder()
            .url(url)
            .post(body)
            .build();

    client.newCall(postRequest).enqueue(new Callback()
    {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e)
        {
            Log.i("TAG", "ERROR - " + e.getMessage());
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException
        {
            if (response.isSuccessful())
            {
                Log.i("LOG", "SUCCESS - " + response.body().string());
            }
            else
            {
                Log.i("LOG", "FAILED. Status Code: " + String.valueOf(response.code));
            }
        }
    });

All help is appreciated!

Upvotes: 0

Views: 1296

Answers (1)

Akın Tekeoğlu
Akın Tekeoğlu

Reputation: 161

You have a missing closing bracket in the request body at java implementation.

"{\"identifier\": \"[email protected]\", \"password\": \"Password\"}"

Upvotes: 2

Related Questions