簡體   English   中英

如何使用帶AsynceTask的Oauth 2.0向自定義api發送http請求

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

我想向自定義api發送http請求。 我有請求詳細信息,它正在使用postman(http客戶端)。 我試圖使用AsyncTask將該請求轉換為android。

我無法理解一些事情:首先,如何發送我擁有的Bearer令牌(oauth 2.0)。 第二,如何送一個傑森身體。 有關請求的所有詳細信息,請訪問以下鏈接: https//web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f

我的“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;
    }

這不起作用,我從服務器獲得身份驗證失敗,感謝您的幫助!

您需要在標題中添加這些對。 並將正文添加為實體。

// 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);

只是一個提示。 查看Retrofit2庫以完成所有這些工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM