Issue Downloading .csv File with POST Request in R

Hi everyone,

I'm trying to download a .csv file from the Diário Oficial da Cidade de São Paulo website using a POST request in R, but I'm encountering difficulties. The downloaded file contains the message "Não há arquivo disponível para essa Data" (No file available for this date), although the file exists.

The llink to the website is this: https://diariooficial.prefeitura.sp.gov.br/md_epubli_controlador.php?acao=edicao_consultar&formato=A

Here is the code I'm using:

library(httr)
library(tidyverse)

baixar_doc_livre <- function(data) {
  url <- "https://diariooficial.prefeitura.sp.gov.br/md_epubli_controlador.php?acao=edicao_download"
  nome_arquivo <- paste0(data, ".csv")
  
  headers <- c(
    "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
    "Accept" = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Encoding" = "gzip, deflate, br, zstd",
    "Accept-Language" = "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
    "Connection" = "keep-alive",
    "Content-Type" = "application/x-www-form-urlencoded",
    "Origin" = "https://diariooficial.prefeitura.sp.gov.br",
    "Referer" = "https://diariooficial.prefeitura.sp.gov.br/md_epubli_controlador.php?acao=edicao_consultar&formato=A",
    "Upgrade-Insecure-Requests" = "1"
  )
  
  body <- list(
    hdnDtaEdicao = data,
    hdnTipoEdicao = "C",
    hdnBolEdicaoGerada = "false",
    hdnInicio = "0",
    hdnFormato = "A"
  )
  
  response <- POST(url, add_headers(.headers = headers), body = body, encode = "form")
  
  if (status_code(response) == 200) {
    writeBin(content(response, "raw"), nome_arquivo)
    print(paste("File", nome_arquivo, "downloaded successfully!"))
  } else {
    print("Failed to download the .csv file.")
  }
}

baixar_doc_livre("06022025")

Could someone help me identify the issue or suggest a solution? Thanks in advance!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.