在 Android 中使用 HttpPost 发送 Bearer Token

我找不到使用我创建的 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 Unauthorized 每次尝试。


牛魔王的故事
浏览 192回答 3
3回答

慕慕森

我正在使用 Volley,但是当我设置标题时,我是这样做的:HashMap<String, String> headers = new HashMap<String, String>();&nbsp; &nbsp; String authValue = "Bearer " + apiToken;&nbsp; &nbsp; headers.put("Authorization", authValue);&nbsp; &nbsp; headers.put("Accept", "application/json; charset=UTF-8");&nbsp; &nbsp; headers.put("Content-Type", "application/json; charset=UTF-8");

森林海

“授权”不应是参数。它是一个标题。HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);String auth = DEFAULT_USER + ":" + DEFAULT_PASS;byte[] encodedAuth = Base64.encodeBase64(&nbsp; 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);

largeQ

为什么不使用OK Http进行网络请求?然后你可以这样做:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;val&nbsp;request&nbsp;=&nbsp;Request.Builder() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.url(yourUrl) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.header("Authorization",&nbsp;"Bearer&nbsp;$yourToken") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.post(yourBody) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.build()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java