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);
Related
I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!
I am trying to insert a new contact in Salesforce using Rest Api but unfortunately getting 400 Bad request exception.While using Postman everything is perfect but via code it is throwing exception. Someone guide me plz where I am wrong.
string new_Contact_url = ConfigurationManager.AppSettings["SalesForceBaseUrl"] + "sobjects/contact";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new_Contact_url);
request.Method = "POST";
request.Headers.Add("Authorization", "Access_Token");
request.ContentType = "application/json; charset=utf-8";
var keyValues = new Dictionary<string, string>
{
{ "LastName", "Nafees" },
{ "Email", "email "},
{ "Tools_User_ID__c", "login_id" }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string postData = js.Serialize(keyValues);
byte[] byteArray = Encoding.UTF8.GetBytes(postData.Trim());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var resp = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var responseBody = (IDictionary<string, object>)serializer.DeserializeObject(resp);
if (!string.IsNullOrEmpty(responseBody["access_token"].ToString()))
{
string id = responseBody["Id"].ToString();
}
Salesforce recently switched from supporting TLS1.0 to TLS1.2.
In your C# code can you add this:
using System.Net;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
The ServicePointManager part should be before you send the request.
i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here
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);
I send Post request by follow code:
try
{
string responseContent;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
// Set Method to "POST"
request.Method = "POST";
// Set the content type of the WebRequest
request.ContentType = "application/x-www-form-urlencoded";
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
// Set the content length
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(requestCommand);
request.ContentLength = byteArray.Length;
// Get the request stream
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (BufferedStream buffer = new BufferedStream(responseStream))
{
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
}
}
}
return responseContent;
}
catch (Exception ex)
{
return ex.Message;
}
}
It's works ok. But the code lines below is so slow.
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
I don't know why! I have spend more time to find out solution, such at set proxy = null,... but no results.
Are there any way to ignore that line. I dont need to receive response data. I have tried replace that lines by:
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Flush();
responseStream.Close();
}
But I can't send Post request correctly and sucessfuly. Please help me. Thanks so much!
If you don't care at all about the response or whether it fails, you can probably queue up the response on a new thread and just ignore it.
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
// now put the get response code in a new thread and immediately return
ThreadPool.QueueUserWorkItem((x) =>
{
using (var objResponse = (HttpWebResponse) request.GetResponse())
{
responseStream = new MemoryStream();
objResponse.GetResponseStream().CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);
}
});