user3077416
user3077416

Reputation: 271

POST Data with HttpURLConnection

I am still newbie as android developer especially about GET/POST data with Oauth 2.0 feature for login script. I can't use deprecated methods like HttpClient and HttpPost for my app with API 23 support below:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();

I have a plan to use HttpURLConnection method like this link but still dunno to add it on my script with request parameters below:

Requests Example:

POST /access_token HTTP/1.1

Host: api.example.com

Cache-Control: no-cache

Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=[client_od]&client_secret=[client_secret]&username=name%40email.com&password=1234

After successfull login I can get response example like below:

"time": 0.2429,
"environment": "DEVELOPMENT",
"status": {
"code": 200,
"description": "OK"
},
"data": {
"access_token": "shddsldshldslkdsklksdldslkdslksdlkds",
"token_type": "Bearer",
"expires_in": 86400,
"refresh_token": "sekhewihewiiewjejwojewojoewhik"
}
}

How I can figure it so I can get response example like above?

Upvotes: 0

Views: 553

Answers (1)

Iamat8
Iamat8

Reputation: 3906

I would suggest to use loopj library which give you RequestParams and AsyncHttpClient to accomplish your task..

Get Jar and explanation from here

    RequestParams params = new RequestParams();
    params.put("username", "james");
    params.put("password", "123456");
    params.put("email", "[email protected]");
    //------add params here-------//

    AsyncHttpClient client = new AsyncHttpClient();
    client.post("IP / URL", params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            try {
                JSONObject json = new JSONObject("");
                //----- parse json 
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            //---failure massage
        }
    });

Upvotes: 1

Related Questions