Sergei B.
Sergei B.

Reputation: 138

Convert JavaScript AJAX to HttpWebRequest code

I need imitate AJAX call to web service in my console application. Is there any way to do this with HttpWebRequest?

Source request:

var webRequest = Sys.Net.WebServiceProxy.invoke('http://webserver.com/WS_Message.asmx', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSuccess, onFailure, userContext, timeout, enableJsonp, jsonpCallbackParameter);

Sample that doesn't work:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://webserver.com/WS_Message.asmx/MyMethod");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

byte[] _bytes= Encoding.UTF8.GetBytes("{p1:aa,p2:bb,p3:123}");

request.ContentLength = _bytes.Length;

Stream stream = request.GetRequestStream();
stream.Write(_bytes, 0, _bytes.Length);
stream.Close();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    Console.WriteLine(reader.ReadToEnd());
}

Upvotes: 0

Views: 1828

Answers (2)

Sergei B.
Sergei B.

Reputation: 138

I had to use Chrome Developer Console to see correct http headers. My issue was related to incorrect JSON string format.

@"{""p1"": ""aa"", ""p2"": ""bb"", ""p3"": 123}"

Upvotes: 0

Menno van den Heuvel
Menno van den Heuvel

Reputation: 1861

It looks like you were calling into a (.NET based) web service in javascript. Why not simply add a web reference to your console app, and call it that way ?

It will be much less work than trying to replicate the web service call manually through an HttpWebRequest.

Upvotes: 1

Related Questions