繁体   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