Sending Bearer Token with HttpPost in Android

▼魔方 西西 提交于 2021-02-04 21:53:24

问题


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.

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

The error I get is 401 Unauthorized on every attempt.


回答1:


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



回答2:


Why don't you use OK Http for networking requests? Then you can do something like this:

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



回答3:


I'm using Volley, but when I set up the headers, I do it with this:

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


来源:https://stackoverflow.com/questions/56402089/sending-bearer-token-with-httppost-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!