Ali Tauseef Reza
Ali Tauseef Reza

Reputation: 53

WebClient is throwing error while calling UploadString()

I have to work on JSON data from API (in my windows app), and I am trying make a POST request using WebClient.UploadString(); Below is my code, but its throwing error, I tried various options but not able to copy the JSON as a string.

string result = "";
        string url = "https://30prnabicq-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia for vanilla JavaScript (lite) 3.24.12;JS Helper 2.24.0;vue-instantsearch 1.5.0&x-algolia-application-id=30PRNABICQ&x-algolia-api-key=dcccebe87b846b64f545bf63f989c2b1";
        string json = "{\"requests\":[{\"indexName\":\"vacatures\",\"params\":\"query=&hitsPerPage=20&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__/ais-highlight__&facets=[\"category\",\"contract\",\"experienceNeeded\",\"region\"]&tagFilters=\"}]}";

        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.Host] = "30prnabicq-dsn.algolia.net";
            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"; 
            client.Headers[HttpRequestHeader.Accept] = "application/json"; 
            client.Headers[HttpRequestHeader.AcceptLanguage] = "en-US,en;q=0.5"; 
            client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate, br"; 
            client.Headers[HttpRequestHeader.Referer] = "https://bouwjobs.be/";
            client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
            client.Headers[HttpRequestHeader.ContentLength] = "249"; 
            client.Headers[HttpRequestHeader.Origin] = "https://bouwjobs.be"; 
            client.Headers[HttpRequestHeader.Connection] = "keep-alive";
            client.Headers[HttpRequestHeader.Cache - Control] = "max-age=0";

            result = client.UploadString(url, "POST", json);
            return result;
        }

Please guide me in correcting my code.

Note - Some restricted headers I have included in my code, but even after commenting out those it is throwing error.

Upvotes: 0

Views: 842

Answers (1)

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

You do not seem uploading a valid Json with WebClient. Double quotes in your inner array facets means your query parameter has ended. Remove quotes from it.

string json = "{\"requests\":[{\"indexName\":\"vacatures\",\"paras\":\"query=&hitsPerPage=20&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__/ais-highlight__&facets=[category,contract,experienceNeeded,region]&tagFilters=\"}]}";

This is valid json and should work fine.

Upvotes: 1

Related Questions