简体   繁体   中英

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.

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

Well, Actually you can't send real AJAX request using HttpClient , but you can simulate it by adding XMLHttpRequest to request header like this:

client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");

Here is a Helper method which requires Microsoft.AspNet.WebApi.Client nuget package:

    private async TResponse CreateHttpRequestAsync<TRequest, TResponse>(Uri uri, TRequest request)
        where TRequest : class
        where TResponse : class, new()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _bearerToken);
            var response = await client.PostAsJsonAsync(uri, request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var json = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<TResponse>(json);
            }
            else if(response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new UnauthorizedException();
            }
            else
            {
                throw new InvalidOperationException();
            }
        }

    }

You can't send an AJAX request using HttpClient. You can send an asynchronous HTTP request if you want.

AJAX is asynchronous JavaScript + XML (it has since become broader to mean Asynchronous JavaScript + other formats eg Json), but it's still fundamentally a browser technology involving JavaScript.

HttpClient doesn't know anything about JavaScript, you'd have to use a WebBrowser control for executing JavaScript.

Update:

Looking back at this question, I find it rather surprising that so many seemingly experienced devs don't understand the term AJAX and confuse it with a simple asynchronous HTTP request, so I think it'd be helpful to provide more info here.

Ajax is short for A synchronous JA vaScript and X ML, it allows web pages to send/receive asynchronous data serialized as XML via XMLHttpRequest s, and then use that data to dynamically update the page without the need to reload the entire page which is all done using JavaScript .

Now over the last few years, XML has lost its luster as the de facto standard of formatting data and JSON is taking its place, and that has affected Ajax too, you typically see data formatted as JSON instead of XML when communicating with servers. So the acronym AJA X wasn't so precise anymore; AJA J was proposed but its use did not become widespread, so people still use the term Ajax when in fact they are not sending/receiving XML, but that's not a very big deal because the two are essentially very similar other than the way the data is formatted:

  • it still involves a JavaScript.
  • a web page/application sending/receiving asynchronous requests.
  • a web browser that supports JavaScript and XMLHttpRequest.

With the above context, I hope its clear that what the OP is trying to do here, and the accepted answer for that matter, has very little to do with Ajax as it doesn't involve any of the above points. It is in fact, just a simple HTTP request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM