gpt4 book ai didi

java - 为什么要在发送http请求之前使用Base64相关算法

转载 作者:可可西里 更新时间:2023-11-01 17:00:03 28 4
gpt4 key购买 nike

我正在做一些关于向 Teamcity 服务器发送 http REST 请求的事情。对于身份验证部分,当我使用下面的代码时,会出现 401 错误。

public class Client {

public static void main(String args[]){
try{
Client client = new Client();
client.sendGet();
//client.sendPost();
}catch(Exception e){
e.printStackTrace();
}
}

String USER_AGENT = "";

private void sendGet() throws Exception {

String url = "http://localhost:80/httpAuth/app/rest/builds";

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("GET");

con.setRequestProperty("User-Agent", USER_AGENT);

String login = "gearon";
String password = "gearonpassword";
String token = login + ":" + password;

con.setRequestProperty ("Authorization", "Basic " + token);

int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

System.out.println(response.toString());
}
}

我通过添加以下代码解决了这个问题

    byte[] tokenArr = StringUtils.getBytesUtf8(token);

String encoded = new String(Base64.encodeBase64(tokenArr));

con.setRequestProperty ("Authorization", "Basic " + token);

但是,我不明白为什么这解决了我的问题。我的用户名或密码中没有任何特殊字符。并且,我在 Eclipse 中通过右键单击项目 --> 属性 --> 资源 --> 文本文件编码 --> UTF-8 将我的项目编码设置为 UTF-8。

getBytesUtf8方法的javadoc是

Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte array.

如果我的项目已经在使用 UTF-8,则此方法应该没有任何值(value)。

对于另一种方法encodeBase64,javadoc是:

Encodes binary data using the base64 algorithm but does not chunk the output.

也许有神奇的地方发生。我在 wiki 中读到了一些关于 Base64 的内容。

这个问题我说不清楚。那么谁能告诉我背后发生了什么。

最佳答案

这是在 RFC 7617 中定义的:

To receive authorization, the client

  1. obtains the user-id and password from the user,
  1. constructs the user-pass by concatenating the user-id, a singlecolon (":") character, and the password,
  1. encodes the user-pass into an octet sequence (see below for adiscussion of character encoding schemes),
  1. and obtains the basic-credentials by encoding this octet sequenceusing Base64 ([RFC4648], Section 4) into a sequence of US-ASCIIcharacters ([RFC0020]).

关于java - 为什么要在发送http请求之前使用Base64相关算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com