在Android中使用HttpPost发送不记名令牌 [英] Sending Bearer Token with HttpPost in Android

查看:67
本文介绍了在Android中使用HttpPost发送不记名令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

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

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on 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未经授权.

The error I get is 401 Unauthorized on every attempt.

推荐答案

授权"不应作为参数.它是标题.

The "Authorization" should not be a parameter. Its a header.

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

这篇关于在Android中使用HttpPost发送不记名令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆