简体   繁体   中英

How to send an http request to custom api using Oauth 2.0 with AsynceTask

I would like to send an http request to custom api. I have the request details, and it is working using postman(http client). Im trying to translate that request to android, using AsyncTask.

I couldnt managed to understand few things: first, how to send the Bearer token that I have(oauth 2.0). the second, how to send a jason body. all the details about the request are in the following link: https://web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f

my "DoInBackground" :

protected Void doInBackground(Void... voids) {
        response = null;
        Log.v("DoInBackground","entered");
        //sending Data
        if (valid) {

            Log.v("ifvaild","entered");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("https://dmyzcsu4e68qfgi56y7l2qu5ky40da2o.ui.nabu.casa/api/services/script/turn_on");
            //httpPost.addHeader("Accept-Language", "he");
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();  
            nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer My Bearer"));
            nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
            nameValuePair.add(new BasicNameValuePair("script.turn_on", "script.gt1"));

            Log.v("nameValue","entered");

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));

            } catch (UnsupportedEncodingException e)

            {
                e.printStackTrace();
            }
            try {
                response = httpClient.execute(httpPost);
                Log.v("HttpClient","entered");
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

this is not working, I get an authentication failure from the server thanks for your help!

You need to add those pairs in the header. And add the body as entity.

// headers
httpPost.addHeader("Authorization", "Bearer My Bearer");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("script.turn_on", "script.gt1");

// body
String bodyString = "{\"data\":1}"; // your json string
StringEntity bodyEntity = new StringEntity(bodyString);
httpPost.setEntity(bodyEntity);

Just a tip. Look into Retrofit2 library to do all of this.

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