[R] help with sockets in R
Christopher Bare
cbare at systemsbiology.org
Wed Sep 22 02:44:56 CEST 2010
Hi R gurus,
I'm trying to use a ReSTful web service from within R. Specifically, I
need to make HTTP PUT requests.
I'm able to make the request and that goes well enough, but I'm having
trouble properly consuming the HTTP response. The problem comes in
when I'm trying to parse out the response body. I get the length of
the response body from the Content-Length header. I then try to use
readChar(con, nchars=content.length).
The result I'm seeing is that the first few characters of the response
body are cut off.
My code looks like this:
http.request <- function(host, path, request, port=80) {
con <- socketConnection(host=host, port=port, open="w+",
blocking=TRUE, encoding="UTF-8")
writeLines(request, con)
write("wrote request", stderr())
flush(stderr())
# build response object
response <- list()
response$status <- readLines(con, n=1)
response$headers <- character(0)
repeat{
ss <- readLines(con, n=1)
write(ss, stderr())
flush(stderr())
if (ss == "") break
key.value <- strsplit(ss, ":\\s*")
response$headers[key.value[[1]][1]] <- key.value[[1]][2]
}
if (any(names(response$headers)=='Content-Length')) {
content.length <- as.integer(response$headers['Content-Length'])
response$body <- readChar(con, nchars=content.length)
}
close(con)
}
response$body ends up with
"e,\"id\":\"some_doc\",\"rev\":\"7-906e06a7744780ef93126adc6f8f10ef\"}\n"
when it should be:
"{\"ok\":true,\"id\":\"some_doc\",\"rev\":\"7-906e06a7744780ef93126adc6f8f10ef\"}"
Is mixing readLines and readChars on the same connection causing bad
juju? If it is, what's the recommended what to do such a thing?
Thanks for any help!!
-Chris
More information about the R-help
mailing list