在Android中使用HttpPost发送承载令牌

时间:2019-05-31 21:54:01

标签: java android httpclient restful-authentication

我找不到使用创建的Bearer令牌通过服务器认证我的应用程序的方法。它与Postman完美搭配。

我尝试使用UTF-8编码,在URL中使用?access_token,尝试了很多我在Stackoverflow上找到的答案。

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.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 eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

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

每次尝试我得到的错误都是401未经授权。

3 个答案:

答案 0 :(得分:1)

“授权”不应是参数。它是标题。

HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);

答案 1 :(得分:0)

您为什么不使用OK Http进行网络请求?然后您可以执行以下操作:

        val request = Request.Builder()
                .url(yourUrl)
                .header("Authorization", "Bearer $yourToken")
                .post(yourBody)
                .build()

答案 2 :(得分:0)

我正在使用Volley,但是在设置标题时,我这样做:

HashMap<String, String> headers = new HashMap<String, String>();
    String authValue = "Bearer " + apiToken;
    headers.put("Authorization", authValue);
    headers.put("Accept", "application/json; charset=UTF-8");
    headers.put("Content-Type", "application/json; charset=UTF-8");