必应搜索API Azure Marketplace Java身份验证

5

我该如何在Java中进行身份验证,以使用Azure Marketplace的新Bing搜索API?迁移指南没有提供有关Java的信息。

1个回答

8
您需要将账户密钥编码为Base64格式,并使用Authorization头在每个请求中传递它。
String bingUrl = "https://api.datamarket.azure.com/Bing/Search/................";

String accountKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);

URL url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);

...

此代码基于在迁移到Windows Azure Marketplace中的Bing搜索API文档中找到的PHP示例。

更新:修改了encodeBase64调用,应该像这样:accountKey +“:”+ accountKey


这种方式似乎是正确的,但是setRequestProperty中的某些内容必须不同,因为这样我会收到响应消息“需要基本身份验证。将帐户密钥输入作为密码。” - Themis Mavridis
你的新代码产生了一个“错误请求”。我也尝试过httpsCon.setRequestProperty("Authorization: Basic",accountKeyEnc);但我再次收到了“需要基本身份验证”的消息...@sandrinodimattia - Themis Mavridis
这段代码有帮助吗?https://github.com/carrot2/carrot2/tree/master/core/carrot2-source-microsoft/src/org/carrot2/source/microsoft - Themis Mavridis
如果您收到了“Bad Request”错误提示,我会认为身份验证已经通过,但实际请求存在问题。请问您使用的完整URL是什么(例如,您是否处理了URL编码)?您发送了哪些数据? - Sandrino Di Mattia
我找到了我的坏请求的问题!我在查询前面放了$...谢谢你的帮助! - Themis Mavridis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接