[英]Sending Bearer Token with HttpPost in Android
我找不到使用創建的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未經授權。
“授權”不應是參數。 它的頭。
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);
為什么不使用OK Http進行網絡請求? 然后,您可以執行以下操作:
val request = Request.Builder()
.url(yourUrl)
.header("Authorization", "Bearer $yourToken")
.post(yourBody)
.build()
我正在使用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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.