我正在发出一个 HttpGet 请求,其中"授权"作为附加持有者令牌的标头。我一直收到 401 未经授权的错误。
我尝试过改造,它不起作用,所以我恢复到基本的 HTTP 客户端。然后经过大量研究发现DefaultHttp存在一些错误。所以我改成了HTTPUrlConnection。即使完成了所有这些操作,我仍然收到未经授权的401错误。我可能在这里做错什么?因为这个错误仍然存在,我决定坚持使用HTTPUrlConnection或DefaultHTTP,远离库。
这是我使用 HttpUrlConnection 的代码
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)
obj.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer" + accessToken;
con.setRequestProperty("Authorization", authString);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("GET request not worked");
}
这是我的 DefaultHttp 请求
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(url);
httpGetRequest.addHeader("Authorization","Bearer"+accessToken);
try {
HttpResponse response = client.execute(httpGetRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
cu 后添加一个空格Bearer
因为它将连接Bearer
与标记作为一个字符串
请使用快速Android网络库,它非常易于使用,您可以在不到5分钟的时间内实现您的逻辑。所以请至少试一试。以下是图书馆的链接:
https://github.com/amitshekhariitbhu/Fast-Android-Networking
问题已解决。我尝试使用改造和默认HttpClient,但由于一些cookie问题,两者都对我不起作用。但是使用 OKHttpClient 很简单,我能够点击服务器并获得响应。
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(mURL)
.addHeader("Authorization", String.format("Bearer %s", bearerToken))
.build();
Response response = client.newCall(request).execute();
return response.body().string();