将 HTTP Basic-Auth 与 Google App Engine URLFetch 服务结合使用
如何指定用户名和密码以使用 App Engine 的 URLFetch 服务(Java 中)?
看来我可以设置 HTTP 标头:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");
Basic-Auth 的适当标头是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是 http 上的基本身份验证标头:
授权:基本 base64 编码(用户名:密码)
例如:
您需要执行以下操作:
为此,您需要获得一个 base64 编解码器 api,例如 Apache Commons 编解码器
This is a basic auth header over http:
Authorization: Basic base64 encoded(username:password)
eg:
You will need to do this:
And to do that you will want to get a base64 codec api, like the Apache Commons Codec
对于那些有兴趣在 Python 中执行此操作的人(就像我一样),代码如下所示:
For those interested in doing this in Python (as I was), the code looks like this:
您在调用 openConnection() 之前设置了一个身份验证器,如下所示,
由于只有一个全局默认身份验证器,因此当您有多个用户在多个线程中执行 URLFetch 时,这并不能很好地工作。如果是这样的话,我会使用 Apache HttpClient。
编辑:我错了。 App Engine 不允许使用身份验证器。即使允许,我们也会遇到全局身份验证器实例的多线程问题。即使您无法创建线程,您的请求仍可能在不同的线程中得到服务。所以我们只需使用此函数手动添加标头,
You set up an Authenticator before you call openConnection() like this,
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.
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,
使用 HttpURLConnection 给了我一些问题(由于某种原因,我尝试连接的服务器不接受身份验证凭据),最后我意识到使用 GAE 的低级 URLFetch 实际上要容易得多API (
com.google.appengine.api.urlfetch
) 如下所示:这有效。
Using
HttpURLConnection
gave 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:This worked.
Apache HttpClient 上有一个用于 App Engine 的包装器,
请浏览帖子 http://esxx.blogspot.com/2009/06/using-apaches-httpclient-on-google-app.html
http://peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-谷歌.html
There is a wrapper on Apache HttpClient for App Engine
please go through the post 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
请注意第一个答案:setRequestProperty 应获取不带冒号的属性名称(“授权”而不是“授权:”)。
Note on the first answer: setRequestProperty should get the property name without the colon ("Authorization" rather than "Authorization:").