java 将 HTTP Basic-Auth 与 Google App Engine URLFetch 服务结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1341081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using HTTP Basic-Auth with Google App Engine URLFetch service
提问by Thilo
How can I specify the username and password for making Basic-Auth requests with App Engine's URLFetchservice (in Java)?
如何指定用户名和密码以使用 App Engine 的URLFetch服务(在 Java 中)发出基本身份验证请求?
It seems I can set HTTP headers:
似乎我可以设置 HTTP 标头:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");
What are the appropriate headers for Basic-Auth?
Basic-Auth 的适当标头是什么?
回答by Zombies
This is a basic auth header over http:
这是 http 上的基本身份验证标头:
Authorization: Basic base64 encoded(username:password)
授权:基本base64编码(用户名:密码)
eg:
例如:
GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
You will need to do this:
你需要这样做:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Basic "+codec.encodeBase64String(("username:password").getBytes());
And to do that you will want to get a base64 codec api, like the Apache Commons Codec
为此,您将需要一个 base64 编解码器 api,例如Apache Commons Codec
回答by Luke Francl
For those interested in doing this in Python (as I was), the code looks like this:
对于那些有兴趣在 Python 中执行此操作的人(就像我一样),代码如下所示:
result = urlfetch.fetch("http://www.example.com/comment",
headers={"Authorization":
"Basic %s" % base64.b64encode("username:pass")})
回答by ZZ Coder
You set up an Authenticator before you call openConnection() like this,
你在像这样调用 openConnection() 之前设置了一个 Authenticator,
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
Since there is only one global default authenticator, this doesn't really work well when you have multiple users doing the URLFetch in multiple threads. I would use Apache HttpClient if that's the case.
由于只有一个全局默认身份验证器,因此当您有多个用户在多个线程中执行 URLFetch 时,这并不能很好地工作。如果是这种情况,我会使用 Apache HttpClient。
EDIT: I was wrong. App Engine doesn't allow Authenticator. Even if it's allowed, we would have the multi-thread issue with a global authenticator instance. Even though you can't create threads, your requests may still get served in different threads. So we just add the header manually using this function,
编辑:我错了。App Engine 不允许使用身份验证器。即使允许,我们也会遇到全局身份验证器实例的多线程问题。即使您无法创建线程,您的请求仍可能会在不同的线程中提供服务。所以我们只需使用这个函数手动添加标题,
import com.google.appengine.repackaged.com.google.common.util.Base64;
/**
* Preemptively set the Authorization header to use Basic Auth.
* @param connection The HTTP connection
* @param username Username
* @param password Password
*/
public static void setBasicAuth(HttpURLConnection connection,
String username, String password) {
StringBuilder buf = new StringBuilder(username);
buf.append(':');
buf.append(password);
byte[] bytes = null;
try {
bytes = buf.toString().getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
String header = "Basic " + Base64.encode(bytes);
connection.setRequestProperty("Authorization", header);
}
回答by alibloomdido
Using HttpURLConnectiongave me some problems (for some reason the server I was trying to connect to didn't accept auth credentials), and finally I realized that it's actually much easier to do using GAE's low-level URLFetch API (com.google.appengine.api.urlfetch) like so:
使用HttpURLConnection给我带来了一些问题(由于某种原因,我尝试连接的服务器不接受身份验证凭据),最后我意识到使用 GAE 的低级 URLFetch API ( com.google.appengine.api.urlfetch)实际上要容易得多,如下所示:
URL fetchurl = new URL(url);
String nameAndPassword = credentials.get("name")+":"+credentials.get("password");
String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());
HTTPRequest request = new HTTPRequest(fetchurl);
request.addHeader(new HTTPHeader("Authorization", authorizationString));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
System.out.println(new String(response.getContent()));
This worked.
这奏效了。
回答by Rahul Garg
There is a wrapper on Apache HttpClient for App Engine
App Engine 的 Apache HttpClient 上有一个包装器
please go through the post http://esxx.blogspot.com/2009/06/using-apaches-httpclient-on-google-app.html
请阅读帖子http://esxx.blogspot.com/2009/06/using-apaches-httpclient-on-google-app.html
http://peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-google.html
http://peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-google.html
回答by Rahul Garg
Note on the first answer: setRequestProperty should get the property name without the colon ("Authorization" rather than "Authorization:").
注意第一个答案:setRequestProperty 应该获取不带冒号的属性名称(“授权”而不是“授权:”)。

