从R调用Watson API

时间:2015-01-23 18:36:40

标签: r ibm-cloud ibm-watson

我在Bluemix上创建了我的语言识别服务,我试图用R来调用它。

enter image description here

http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/language-identification/identify

这是我正在使用的代码:

library(httr)
login <- "https://gateway.watsonplatform.net/laser/service/api/v1/txtlid/bb0e9e07-cf44-4e95-a5a1-3fb0d53ac98f"
pars <- list(
  sid="lid-generic",
  txt="how are you"
)
POST(login, authenticate("my_username", "my_password@p"), body = pars)

我得到的回复当然不是预期的,错误是401.有谁知道我在做错了什么?

我得到的结果是:

Response [https://gateway.watsonplatform.net/laser/service/api/v1/txtlid/bb0e9e07-cf44-4e95-a5a1-3fb0d53ac98f]
  Date: 2015-01-23 12:29
  Status: 401
  Content-type: text/html
  Size: 252 B
--------------------------4bd32c1a987ed099
Content-Disposition: form-data; name="sid"

lid-generic
--------------------------4bd32c1a987ed099
Content-Disposition: form-data; name="txt"

how are you
--------------------------4bd32c1a987ed099--

2 个答案:

答案 0 :(得分:2)

以下是一些&#34; R&#34;这里的代码片段可能会有所帮助:     https://github.com/rustyoldrake/R_Scripts_for_Watson

简要说明 - 下面的语法显示了使用&#34; username_password&#34;使用getURL(RCurl)和POST(HTTR)

### Initialize Creds and URL
base_url = "https://gateway.watsonplatform.net/dialog-beta/api/v1" 
username = "9XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX" # from Bluemix Service Credentials
password = "123123123123"
username_password = paste(username,":",password,sep="")


###### FUNCTION - CHECK CLASSIFIER STATUS (DIALOG Example)
watson.nlc.checkclassifierstatus <- function(classifier_id) {
  return(
    getURL(paste(base_url,classifier_id,sep=""),userpwd = username_password)
  )
}

###### FUNCTION CREATE NEW CLASSIFIER  (NLC Example)
watson.nlc.createnewclassifier <- function(file,classifiername) {
  return(POST(url="https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers",
         authenticate(username,password),
         body = list(training_data = upload_file(file),
                     training_metadata = paste("{\"language\":\"en\",\"name\":",classifiername,"}",sep="") 
         )))}

答案 1 :(得分:1)

http 401表示身份验证问题;可能是您创建了一个用户标识/密码,该用户标识/密码已分配给您的服务实例。您需要在R。

中的HTTP调用中将这些作为用户标识/密码传递

您似乎在代码中执行此操作:

POST(login, authenticate("my_username", "my_password@p"), body = pars)

我想知道您是否只是将错误的用户ID /密码复制到authenticate()来电中的这些值中。