将 HTTP Basic-Auth 与 Google App Engine URLFetch 服务结合使用
问题描述:
如何指定用于使用 App Engine 的 URLFetch 服务(在 Java 中)?
How can I specify the username and password for making Basic-Auth requests with App Engine's URLFetch service (in Java)?
似乎我可以设置 HTTP 标头:
It seems I can set HTTP headers:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");
Basic-Auth 的合适标头是什么?
What are the appropriate headers for Basic-Auth?
答
这是一个基于 http 的基本身份验证标头:
This is a basic auth header over http:
授权:基本 base64 编码(用户名:密码)
Authorization: Basic base64 encoded(username:password)
例如:
GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
您需要这样做:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Basic "+codec.encodeBase64String(("username:password").getBytes());
为此,您需要获得一个 base64 编解码器 API,例如 Apache Commons Codec
And to do that you will want to get a base64 codec api, like the Apache Commons Codec