As I have gone through the examples,I have come across only asynchronous http web request having callback methods,like:-
private void getList(string restApiPath, Dictionary<string, string> output, Type type, string label)
{
webRequest = (HttpWebRequest)WebRequest.Create(restApiPath);
path = restApiPath;
labelValue = label;
webRequest.Method = "POST";
webRequest.ContentType = Globals.POST_CONTENT_TYPE;
webRequest.Headers["st"] = MPFPConstants.serviceType;
webRequest.BeginGetRequestStream(result =>
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(result);
// Create the post data
string reqData = Utils.getStringFromList(output);
string encode = RESTApi.encodeForTokenRequest(reqData);
byte[] byteArray = Encoding.UTF8.GetBytes(encode);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallbackForSpecificConditions), request);
}, webRequest);
}
private void GetResponseCallbackForSpecificConditions(IAsyncResult ar)
{
//code
}
Kindly Suggest me if we can make a synchronous httpwebrequest for wp8?
Why not try this, it works in a Desktop app:
using (Stream TextRequestStream = UsedWebRequest.GetRequestStream())
{
TextRequestStream.Write(ByteArray, 0, ByteArray.Length);
TextRequestStream.Flush();
}
HttpWebResponse TokenWebResponse = (HttpWebResponse)UsedWebRequest.GetResponse();
Stream ResponseStream = TokenWebResponse.GetResponseStream();
StreamReader ResponseStreamReader = new StreamReader(ResponseStream);
string Response = ResponseStreamReader.ReadToEnd();
ResponseStreamReader.Close();
ResponseStream.Close();
Why not try restsharp?
sample POST code looks like,
RestClient _authClient = new RestClient("https://sample.com/account/login");
RestRequest _credentials = new RestRequest(Method.POST);
_credentials.AddCookie(_cookie[0].Name, _cookie[0].Value);
_credentials.AddParameter("userLogin", _username, ParameterType.GetOrPost);
_credentials.AddParameter("userPassword", _password, ParameterType.GetOrPost);
_credentials.AddParameter("submit", "", ParameterType.GetOrPost);
RestResponse _credentialResponse = (RestResponse)_authClient.Execute(_credentials);
Console.WriteLine("Authentication phase Uri : " + _credentialResponse.ResponseUri);
Related
I want to post authentication details to a remote server, sending username, database name and password. My server is running on Ubuntu. But i get error Invalid JSON data: ''
"POST / HTTP/1.1" 400 -
I am new to working on this platform, help me with where i am doing it wrong. Below is my code:
private void SendDataButton_Click(object sender, RoutedEventArgs e)
{
string url = "http://200.84.100.211:9875";
string call = url + "/web/session/authenticate";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(call) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(SendData), request);
}
void SendData(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
string postData = "{'db':'demo_shruti','login':'admin','password':'admin'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), myRequest);
}
void FinishWebRequest(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
string responseString = "";
Stream streamResponse = response.GetResponseStream();
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
streamResponse.Close();
reader.Close();
response.Close();
string result = responseString;
}
I'm trying to post data to a web server with such code:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
//request.CookieContainer = new CookieContainer();
//request.CookieContainer.Add(new Uri(uri), new Cookie());
string postData = parameters.ToQueryString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream dataStream = await request.GetRequestStreamAsync())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = await request.GetResponseAsync();
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
return await reader.ReadToEndAsync();
}
}
catch (Exception e)
{
return e.Message + e.StackTrace;
}
Those bits of information that I found on the Internet suggest that it's because response headers are incorrect, but it's not for sure.
Could you please tell how to do http post request with parameters and if suggestion described above is correct, how to tell system.net not to check response headers?
This is how I'm calling this method:
Dictionary<string, string> par = new Dictionary<string, string>();
par.Add("station_id_from", "2218000");
par.Add("station_id_till", "2200001");
par.Add("train", "112Л");
par.Add("coach_num", "4");
par.Add("coach_class", "Б");
par.Add("coach_type_id", "3");
par.Add("date_dep", "1424531880");
par.Add("change_scheme", "0");
debugOutput.Text = await Requests.makeRequestAsync("http://booking.uz.gov.ua/purchase/coach", par);
I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()
I have a PHP web service using JSON that I need to post requests to from a Silverlight application. I had used the HttpWebRequest class before, in a regular C# application and it worked flawlessly. In my Silverlight application, however, the callbacks for the BeginGetRequestStream and BeginGetResponse methods are not getting called.
I tried testing it out in about every way without success. Note that the data I am sending is not long - just a 32 character string most of the time. I checked if the callbacks were getting called at all, and they weren't being called. Here is my code:
public void Request(Command cmd, Dictionary<string, string> data)
{
Dictionary<string, object> fullRequest = new Dictionary<string,object>();
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringWriter writer = new StringWriter(new StringBuilder());
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, fullRequest);
string query = "query=" + writer.ToString();
request.ContentLength = query.Length;
request.ContentType = "text/json";
_queue.Enqueue(new KeyValuePair<Command, string>(cmd, query));
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
public void GetRequestStreamCallback(IAsyncResult target)
{
HttpWebRequest request = (HttpWebRequest)target.AsyncState;
Stream postStream = request.EndGetRequestStream(target);
string postData = "";
//not sure why I have to do this. in the Silverlight documentation
//Queue<> is supposed to have the SyncRoot property
//but I get an error if I just try _queue.SyncRoot
lock ((_queue as ICollection).SyncRoot)
{
postData = _queue.Dequeue().Value;
}
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
public void GetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
JsonSerializer serializer = new JsonSerializer();
Dictionary<string, object> responseData = new Dictionary<string, object>();
responseData = (Dictionary<string, object>)serializer.Deserialize(new StringReader(responseString), typeof(Dictionary<string, object>));
if (_data.ContainsKey(responseData["key"] as string))
{
_data[responseData["key"] as string] = responseData;
}
else
{
_data.Add(responseData["key"] as string, responseData);
}
I also tried this:
IAsyncResult resultRequest = request.BeginGetRequestStream(null, null) as IAsyncResult;
Stream postStream = request.EndGetRequestStream(resultRequest );
To get the stream synchronously (yes, bad style, I just wanted to see if it will work). No success .
Thanks in advance.
I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()