[英]Should i convert a file to Base64 before or after sending it to the backend?
[英]Why should I use Base64 related algorithm before sending the http request
我正在做一些关于向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);
但是,我无法弄清楚为什么这解决了我的问题。 我的用户名或密码中没有任何特殊字符。 并且,我通过右键单击项目 - >属性 - >资源 - >文本文件编码 - > UTF-8,将我的项目编码设置为Eclipse中的UTF-8。
getBytesUtf8
方法的javadoc是
使用UTF-8字符集将给定字符串编码为字节序列,将结果存储到新的字节数组中。
如果我的项目已经使用UTF-8,则此方法不应添加任何值。
对于另一种方法encodeBase64
,javadoc是:
使用base64算法对二进制数据进行编码,但不会对输出进行分块。
也许有惊人的发生。 我在wiki中阅读了一些关于Base64的内容
我不能说清楚这个问题。 所以有人能告诉我背后发生了什么。
这在RFC 7617中定义:
要获得授权,客户
从用户获取用户标识和密码,
通过连接user-id,单个冒号(“:”)字符和密码来构造用户传递,
将用户传递编码为八位字节序列(有关字符编码方案的讨论,请参见下文),
并通过使用Base64([RFC4648],第4节)将此八位字节序列编码为US-ASCII字符序列([RFC0020])来获取基本凭证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.