ConvertAPI - 使用 WebClient C# 抛出 (400) 错误请求的 WEB 到 PDF

ConvertAPI - WEB to PDF using WebClient C# throws (400) Bad Request

我在调用 ConvertApi web to Pdf 时收到错误“(400) Bad Request”Api。

 using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var response = client.UploadString("https://v2.convertapi.com/web/to/pdf?secret=" + Secret + "&Url=" + value + "&ConversionDelay=" + ConversionDelay, "");
                var ocontent3 = JsonConvert.DeserializeObject<FileList>(response);
                byte[] result = ocontent3.Files[0].FileData;
            }

ConvertAPI 和许多其他使用二进制数据运行的 Rest Api 支持多部分或 application/octet-stream(二进制文件)响应,最好使用二进制响应而不是 json(文本) 在 C# 中。它会更快 - 响应主体会更小,下载时间更短并且不需要从 JSON Base64 解码二进制数据。

所以代码可以是

        const string secret = "<YourSecret>";
        const string url = "http://www.google.com";
        const int conversionDelay = 1;
        const string fileToSave = @"C:\Projects\_temp\test1.pdf";

        using (var client = new WebClient())
        {
            client.Headers.Add("accept", "application/octet-stream");
            var response = new byte[] { };
            try
            {
                response = client.UploadValues("https://v2.convertapi.com/web/to/pdf?secret=" + secret, "POST", new NameValueCollection
                {
                    { "Url", url },
                    { "ConversionDelay", conversionDelay.ToString() }
                });
            }
            catch (WebException e)
            {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                Console.WriteLine("Body : {0}", new StreamReader(e.Response.GetResponseStream()).ReadToEnd());
            }

            if (response != null)
                File.WriteAllBytes(fileToSave, response);
        }