Search code examples
c#dotnet-httpclient

How to send Ajax request, using HttpClient


I have a website that send an Ajax request to check validation of a number. I want send that request in my WPF application, using HttpClient.

It use post method, and here is the request url: http://sim.mci.ir/chk-number-availability

Here is the headers:

Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 18
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: _ga=GA1.2.589400539.1410935105; JSESSIONID=33719B6BDA36C7C23A96B5E73F602B08; _gat=1
Host: sim.mci.ir
Pragma: no-cache
Referer: http://sim.mci.ir/first-step
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
X-Requested-With: XMLHttpRequest

And here is the only value:

number=09122175567

I used SendAsync() and PostAsync() methods in common ways, but it doesn't work. I think the problem is in request headers.


Solution

  • HttpClient client = new HttpClient();
    var content = new FormUrlEncodedContent(new Dictionary<string, string>() { 
        { "number", "09129457000" } 
    });
    client.DefaultRequestHeaders.Referrer = new Uri("http://sim.mci.ir/first-step");
    
    var resp = await client.PostAsync("http://sim.mci.ir/chk-number-availability", content);
    var repsStr = await resp.Content.ReadAsStringAsync();
    

    This will return false string