Оператор curl POST для RCurl или httr

У меня есть рабочий оператор curl для отправки файла в службу пакетного геокодирования Nokia HERE...

curl -X POST -H 'Content-Type: multipart/form-data;boundary=----------------------------4ebf00fbcf09' \
     --data-binary @example.txt \
     'http://batch.geocoder.cit.api.here.com/6.2/jobs?action=run&[email protected]&maxresults=1&language=es-ES&header=true&indelim=|&outdelim=|&outcols=displayLatitude,displayLongitude,houseNumber,street,district,city,postalCode,county,state,country,matchLevel,relevance&outputCombined=false&app_code=AJKnXv84fjrb0KIHawS0Tg&app_id=DemoAppId01082013GAL'

Я пробовал это:

library(RCurl) 
url <- "http://batch.geocoder.cit.api.here.com/6.2/jobs?    action=run&[email protected]&maxresults=1&language=es-ES&header=true&indelim=|&outdelim=|&outcols=displayLatitude,displayLongitude,houseNumber,street,district,city,postalCode,county,state,country,matchLevel,relevance&outputCombined=false&app_code=AJKnXv84fjrb0KIHawS0Tg&app_id=DemoAppId01082013GAL'" 
postForm(url, file=fileUpload(filename="example.txt",
                 contentType="multipart/form-data;boundary=----------------------------4ebf00fbcf09"))

И это:

library(httr)
a <- POST(url, body=upload_file("example.txt", type="text/plain"),
          config=c(add_headers("multipart/form-data;boundary=----------------------------4ebf00fbcf09")))
content(a)

Используя этот файл как example.txt: https://gist.github.com/corynissen/4f30378f11a5e51ad9ad

Есть ли способ сделать это свойство в R?


person cory    schedule 28.10.2014    source источник
comment
Попробуйте запустить curl с -v (подробный флаг) и httr::POST с verbose() и сравнить результат. Это поможет вам понять, чем отличаются запросы.   -  person hadley    schedule 29.10.2014
comment
Похоже, мне нужно указать параметр --data-binary в файле httr. Есть ли способ сделать это?   -  person cory    schedule 29.10.2014
comment
Вам нужно выяснить, что делает эта опция.   -  person hadley    schedule 29.10.2014
comment
Когда данные загружаются с использованием параметра --data, символы новой строки и возврата каретки удаляются... что для меня является проблемой. Когда данные загружаются с использованием параметра --data-binary, файл не обрабатывается.   -  person cory    schedule 29.10.2014


Ответы (2)


Я не разработчик Nokia, и я предполагаю, что это не ваши настоящие кредиты API. Это должно помочь вам продвинуться дальше с httr:

url <- "http://batch.geocoder.cit.api.here.com/6.2/jobs"

a <- POST(url, encode="multipart",                      # this will set the header for you
          body=list(file=upload_file("example.txt")),   # this is how to upload files
          query=list(
            action="run",
            mailto="[email protected]",
            maxresults="1",
            language="es-ES",                           # this will build the query string
            header="true",
            indelim="|",
            outdelim="|",
            outcols="displayLatitude,displayLongitude", # i shortened this for the example
            outputCombined="false",
            app_code="APPCODE",
            app_id="APPID"), 
          verbose())                                    # this lets you verify what's going on

Но я не могу быть уверен, что не зарегистрируюсь (и нет времени на это).

person hrbrmstr    schedule 28.10.2014
comment
Это сближает меня. Я получаю ошибку 400 неверных запросов. Я думаю, что мне не хватает требования отправить полезную нагрузку с использованием параметра --data-binary. Страница 20 документа пакетного геокодера Nokia HERE... %20Guide.pdf" rel="nofollow noreferrer">developer.here.com/documentation/download/batch_geocoding_nlp/ - person cory; 28.10.2014

Это решение основано на решении hrbrmstr bod <- paste(readLines("example.txt", warn=F), collapse="\n") a <- POST(url, encode="multipart", # this will set the header for you body=bod, # this is how to upload files query=list( action="run", mailto="[email protected]", maxresults="1", language="es-ES", # this will build the query string header="true", indelim="|", outdelim="|", outcols="displayLatitude,displayLongitude,houseNumber,street,district,city,postalCode,county,state,country,matchLevel,relevance", # i shortened this for the example outputCombined="false", app_code="AJKnXv84fjrb0KIHawS0Tg", app_id="DemoAppId01082013GAL"), #config=c(add_headers("multipart/form-data;boundary=----------------------------4ebf00fbcf09")), verbose()) # this lets you verify what's going on content(a)

Проблема, которую мне пришлось обойти, заключалась в том, что обычный процесс загрузки разделяет разрывы строк... но они нужны мне для работы API (опция --data-binary в curl делает это). Чтобы обойти это, я вставляю данные в виде строки после их чтения с помощью readLines().

person cory    schedule 29.10.2014