【发布时间】:2015-07-02 17:13:22
【问题描述】:
我正在尝试连接到交易 API,并且我已成功发出 GET 请求,但是当我尝试发出 POST 请求时,我不断收到来自 API 的错误消息。我已经在互联网和论坛中搜索了答案,但所有类似的问题都没有得到解决。
这是我正在使用的 R 脚本:
# Call the required packages
library(ROAuth)
library(RJSONIO)
library(XML)
# Set your application keys
cKey <- 'xxxx'
cSecret <- 'xxxx'
oKey <- 'xxxx'
oSecret <- 'xxxx'
# Set the API endpoint
tkURL <- "https://api.tradeking.com/v1/accounts/xxxxxxxx/orders/preview.xml"
# Create the OAuth connection - this is straight from the ROAuth documentation on CRAN
credentials <- OAuthFactory$new(consumerKey = cKey,
consumerSecret = cSecret,
oauthKey = oKey,
oauthSecret = oSecret,
needsVerifier = FALSE,
signMethod='HMAC')
# Update the connection so the handshake is TRUE
credentials$handshakeComplete <- TRUE
# Create FIXML
doc <- newXMLDoc()
root <- newXMLNode('FIXML', namespaceDefinitions = 'http://www.fixprotocol.org/FIXML-5-0-SP2',
newXMLNode('Order', attrs=c(TmInForce='0', Typ='1', Side='1', Acct='xxxxxxxx'),
newXMLNode('Instrmt', attrs=c(SecTyp='CS', Sym='FAS')),
newXMLNode('OrdQty', attrs=c(Qty='1'))), doc=doc)
newFIXML = saveXML(doc, encoding='UTF-8')
newFIXML
# Post order
response <- credentials$OAuthRequest(tkURL, method = "POST", newFIXML)
response
当我运行它时,我得到这个响应:
"<response id=\"-3491729f:14e4f104ddc:7f50\">\n\t
<type>Error</type>\n\t
<name>ScriptFailure</name>\n\t
<description></description>\n\t
<path>/v1/accounts/xxxxxxxx/orders/preview.xml</path>\n</response>"
attr(,"Content-Type")
charset
"application/xml" "UTF-8"
我与 API 的人交谈,他给出了这些建议,但说他对 R 代码无能为力:
我不熟悉 R,所以我可能不会提供太多帮助 代码部分。至于响应ID,似乎标头是 与 fixml 一起错误地发送到请求正文中。 此外,fixml 似乎是编码的,它不应该是。这更 像 xml 或 text 和内容类型应该反映在你的 请求,以便它不会尝试对其进行编码。代替 Content-Type:application/x-www-form-urlencoded,你应该试试 内容类型:文本/xml。这里(粘贴在下面)是我们从您那里得到的 请求:
Headers:
Host:api.tradeking.com Content-Length:668 Accept:*/* Content-Type:application/x-www-form-urlencoded
Body:
=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%0A%3CFIXML%20xmlns%3D%22http%3A%2F%2Fwww.fixprotocol.org%2FFIXML-5-0-SP2%22%3E%0A%20%20%3COrder%20TmInForce%3D%220%22%20Typ%3D%221%22%20Side%3D%221%22%20Acct%3D%22xxxxxxxx%22%3E%0A%20%20%20%20%3CInstrmt%20SecTyp%3D%22CS%22%20Sym%3D%22FAS%22%2F%3E%0A%20%20%20%20%3COrdQty%20Qty%3D%221%22%2F%3E%0A%20%20%3C%2FOrder%3E%0A%3C%2FFIXML%3E%0A&oauth_consumer_key=xxxx&oauth_nonce=xxxx &oauth_signature_method=HMAC-SHA1&oauth_timestamp=1435846001&oauth_token=xxxx&oauth_version=1.0&oauth_signature=xxxx%2xxxx%3D
我将如何在代码中解决这个问题?
【问题讨论】:
-
顺便说一句,我正在使用 API 文档指定的 ROAuth 0.9.2
-
这主要是在黑暗中拍摄,但试试这个:
credentials$OAuthRequest(tkURL, method = "POST", postfields=newFIXML, httpheader=list('Content-Type'='text/html'))。另外,我不知道编码部分