Using REST PUT in C# - c#

I am working with a REST API and I am trying to do a PUT method to it. I found this code I was going to give a try:
static void Main()
{
string xml = "<xml>...</xml>";
byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/");
request.Method = "PUT";
request.ContentType = "text/xml";
request.ContentLength = arr.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(arr, 0, arr.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string returnString = response.StatusCode.ToString();
Console.WriteLine(returnString);
}
One thing I want to do if possible, and can't seem to find anything about it. I would like to pass the data of text fields so, txtEmail.Text, txtFirstName.Text, etc. Is this possible? If, so how would I go about doing this? Does this code look like it would work? Unfortunately the API I'm working with has very very little documentation. Thanks!

The code lines
Stream dataStream = request.GetRequestStream();
dataStream.Write(arr, 0, arr.Length);
dataStream.Close();
do write something to the remote website. The request stream is the way to provide data to the server, so you would create a string / object that you write to the stream to transfer to the server. In your example <xml>...</xml> is sent to the server.

Related

Call Http Post method in c# passing the Method name

I have a problem in "translating" this HTML page into c # code.
I have to pass an xml file to a production machine and I would like to do it from a c # application instead of manually, as shown in the attached screenshot.
I wrote this code c #:
WebRequest request = WebRequest.Create(#"http://Machine_IP/JTI/");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(d.InnerXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
}
I can't figure out how to pass name = "ImportJobs".
If I make a "generic" POST, the machine does not receive the xml file.
I should do a POST as an ImportJobs method.
The supplier, as specifications, gives me the following:
Request
HTTP method: POST
Encryption type (Enctype): Multipart/form-data
URL: http://MachineName/JTI
Command: ImportJobs
Parameters: None
Multipart data section:The XML job description
Response
Data none
Can anyone help me?
thanks a lot
HTML Example

Asynchronous web Post API call from c#

I am writing the code as :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(qry);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
request.ContentLength = 0;
byte[] data = Encoding.UTF8.GetBytes(crsAdapterXML.ToString());
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
Stream objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
result = Convert.ToString(objReader.ReadLine());
I need to make this call asyncronous. Can anyone help me with this.
Using HttpWebRequest is kinda old school way of doing HTTP requests nowadays.
There are libraries which provide better APIs to do this.
I recommend you to try Microsoft's HttpClient (System.Net.Http) or RestSharp.
There are probably many more but those are the ones I know and didn't have problems with.
Both provide async API so you can asynchronously wait for a response.
I don't have much experience with HttpWebRequest but it seems it also exposes async variations of its methods like GetResponseAsync or GetRequestStreamAsync

HttpWebRequest needs to wait 5 seconds to work properly in PUT method

I am trying to use an API and I don't have any problems with GET and POST but PUT isn't working. I tried with a lot of different examples and finally by chance I discovered that waiting more that 5 seconds (with 5000ms it is not working and with 5100ms it does) it starts working properly. But why is that happening? And how can I avoid this? 5 seconds for each registry update is to much waiting and I really don't understand why POST works well without waiting and PUT needs 5 seconds to work.
Here I put the method that I am using with the Thread.Sleep(5100). As I said without this line when I make WebResponse response = request.GetResponse(); gives me an error.
public void call(string url, object jsonObj)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(urlSplio);
// Create POST data and convert it to a byte array.
request.Method = "PUT";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["User"], "WebConfigurationManager.AppSettings["Key"]");
string json = JsonConvert.SerializeObject(jsonObj);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// Set the ContentLength property of the WebRequest.
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();
Thread.Sleep(5100);
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
I think you might want to rewrite the response stream code
Take a look at this walkthrough on MS MS walkthrough
private byte[] GetURLContents(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
// Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
using (WebResponse response = webReq.GetResponse())
{
// Get the data stream that is associated with the specified URL.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
responseStream.CopyTo(content);
}
}
// Return the result as a byte array.
return content.ToArray();
}

WebRequest.GetRequestStreamAsync() method timesout each time for MNS access token

I am trying to get the access token from MNS for Push notifications and the WebRequest.GetRequestStreamAsync() method timesout each time. Any suggestions?
Reference: http://msdn.microsoft.com/en-us/library/windows/apps/hh913756.aspx
Below is the code I use
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("https://login.live.com/accesstoken.srf");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
SID,
SECRET_KEY);
byte[] data = Encoding.UTF8.GetBytes(postString);
Stream newStream = await webRequest.GetRequestStreamAsync();
newStream.Write(data, 0, data.Length);
Try rewriting it like this and see if it makes a difference. I've sometimes had problems with HttpWebRequest where WebRequest worked fine. Also make sure you close your streams.
WebRequest webRequest = WebRequest.Create("https://login.live.com/accesstoken.srf");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
SID,
SECRET_KEY);
byte[] data = Encoding.UTF8.GetBytes(postString);
Stream newStream = await webRequest.GetRequestStreamAsync();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = webRequest.GetResponse();
StreamReader requestReader = new StreamReader( response.GetResponseStream() );
string webResponse = requestReader.ReadToEnd();
response.Close();
Call .ConfigureAwait(false) on your Async method.
This blog post should explain the why and how.
We had the same problem and it turned out to be a problem in different place than one would originally guess.
You need to .Dispose() or at least .Close() the response that you get from .GetResponseAsync, otherwise the next call to .GetRequestStreamAsync hangs.
It seems that the code behind this holds some limited (rather low) amount of sockets or locks, that disallow further requests to even begin until previous request has completed.

post data and get back response in asp.net

i am trying to post a data to a website and get the response back from the server. This is the code that i am using:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.indianrail.gov.in/train_Schedule.html");
((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:9.0) Gecko/20100101 Firefox/9.0";
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = lccp_trnname.Text;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
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();
// Get the response.
try
{
WebResponse response = request.GetResponse();
// Display the status.
Response.Write(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Response.Write(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException ee)
{
Label1.Text = ee.Message;
}
instead of getting the reply back from the server, i am getting redirected to the same webpage in which i am posting the data. Plz help me if anyone has got any idea as what has gone wrong with my code. i've been trying since long back but all efforts went in vain. So plz help
You must post data to http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi instead of http://www.indianrail.gov.in/train_Schedule.html
UPDATE:
The second problem is that you are not sending name of "lccp_trnname" parameter in data. This will make it work:
string postData = "lccp_trnname=" + lccp_trnname.Text;

Categories

Resources