【发布时间】:2014-09-16 23:05:01
【问题描述】:
我不懂 Java,也没有在 Google 或试错测试中取得成功......
如果只在命令行上使用 CURL 进行 RESTful API 身份验证,我将如何编写它? (php 或 perl 解决方案也可以)
此代码来自文档,但我不打算使用 Java,需要翻译它。
URL url = new URL("http://www.thingsandstuff.com/resfulness/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// i don't know if this is relevant to my question or not...
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// this is what i think might be the problem...
String userNamePassword = "myusername:mypassword";
userNamePassword =
new String(org.apache.commons.codec.binary.Base64.encodeBase64(userNamePassword
.getBytes()));
conn.setRequestProperty("Authorization", userNamePassword);
我总是收到 401 未经授权的错误。
我一直在玩标题参数-H。我不知道我正在做的事情是否不起作用,因为我确实没有正确进行身份验证,或者是否是其他原因。数据是 xml,我正在用一些非常简单/直接的东西进行测试。我假设即使我的 data/xml/post 不正确,它也会返回错误而不是未经授权。
# bXl1c2VybmFtZTpteXBhc3N3b3Jk == myusername:mypassword base64 encoded....
curl -H "bXl1c2VybmFtZTpteXBhc3N3b3Jk" -d "<datums>" -X POST http://www.thingsandstuff/restfulness/post
curl -H "bXl1c2VybmFtZTpteXBhc3N3b3Jk" -d "<datums>" -X POST http://www.thingsandstuff/restfulness/post
# and like this... with encoded things and not encoded things...
curl -d "<datums>" -X POST http://user:password@www.thingsandstuff.com/restfulness/post
curl -u user:password -d "<datums>" -X POST http://www.thingsandstuff.com/restfulness/post
对于所有这三个,我都尝试过只对密码进行编码,两者都在一起,都分开,两者都没有......而且我确信我的用户名确实有 \ 并且密码没有帮助以! 结尾,但我认为,当我不对其进行编码时,我正在正确地转义。
而curl man page 表示-d will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded,这意味着我不需要传递额外的标题来说明内容类型,对吧?基本上......我只部分知道我在做什么,但它不起作用,有太多我不知道的事情足以隔离我的问题,甚至可能纠正它(是的,刚好够危险) .
【问题讨论】:
-
也许...我需要两者都做?
-u和-H?那是一回事吗?
标签: java rest authentication curl restful-authentication