Posting to and Receiving data from API using httr in R

我是研究僧i 提交于 2019-12-19 04:23:23

问题


I'm trying to access the US Census Geocoder batch address API, found here: http://geocoding.geo.census.gov/geocoder/

I've also gone through the documentation for the API here: http://geocoding.geo.census.gov/geocoder/Geocoding_Services_API.pdf

I'm trying to use the httr package in R to post a batch csv file of formatted addresses using this format: Unique ID, Street address, City, State, ZIP I've tried the single address request version using getURL from RCurl and that works fine, but postForm doesn't seem to submit the file in the right way. The code I'm using right now seems to post the request correctly, but I'm not getting any geocoded data back.

curlhandle <- handle("http://geocoding.geo.census.gov/geocoder/geographies/addressbatch", 
  cookies = TRUE)

# using fileUpload from RCurl instead of upload_file from httr
upload3  <- fileUpload(contents = address100, contentType = "file")

test <- POST(url="http://geocoding.geo.census.gov/geocoder/geographies/addressbatch", 
  body = list(addressFile = upload3,
         benchmark = "Public_AR_Census2010",
         vintage="Census2010_Census2010"), 
  encode = "multipart",
  handle = curlhandle, 
  followLocation = TRUE,
  verbose = TRUE)

Is my request missing something? I'm not sure if I should be using writefunction & writedata in this case. Any help would be appreciated!


回答1:


You seem to have a weird mix of RCurl and httr. Here's how I'd write the request:

req <- POST(
  "http://geocoding.geo.census.gov/geocoder/geographies/addressbatch", 
  body = list(
    addressFile = upload_file(address100),
    benchmark = "Public_AR_Census2010",
    vintage = "Census2010_Census2010"
  ), 
  encode = "multipart",
  verbose())
stop_for_status(req)
content(req)

(also "file" is not a valid mime type)



来源:https://stackoverflow.com/questions/27048361/posting-to-and-receiving-data-from-api-using-httr-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!