C# write user defined string to web server location - c#

Can you kindly educate me in how can I see the string that I have created, written in the web server location, using c#.
The output I see in the file, that I write in the server location has only the "Date", "Time" and after 4 commas "my IP address"
somthing like this: 2013/11/12,00:20:56,,,,,x.x.x.x,
I would like to see my created string written in the places where we see the commas.
Here is my code:
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(""www.xyz.com/.../....MyUrlLocation");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = Environment.UserName + "," + sw.Elapsed.ToString() + "," + NumberOFProperties.ToString();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(postData);
//byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "PUT";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
bool bIfCanWrite = dataStream.CanWrite;
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// 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();
string strLine = reader.ReadLine();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

Related

Push data into gmail Streak through c#

I am trying to push data into gmail streak through its API in c#,
basically i am trying to create pipeline in streak through API but it gives 400 Bad Request error but I am passing all the data according to given in its website link :- https://streak.readme.io/reference#create-a-pipeline
Code -
try
{
CookieContainer myContainerpush = new CookieContainer();
HttpWebRequest requestpush = (HttpWebRequest)WebRequest.Create("https://www.streak.com/api/v1/pipelines/");
requestpush.Method = "POST";
requestpush.Credentials = new NetworkCredential("gh0b9shff5f77e310cea", "");
String encodedAllPipelines = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("ee3deb0b9f7c4d6c92f5f5f77e310cea:"));
requestpush.Headers.Add("Authorization", "Basic " + encodedAllPipelines);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
requestpush.CookieContainer = myContainerpush;
requestpush.PreAuthenticate = true;
string postData = "{ name:'Hiring', teamWide: false,fieldNames: ['Test'],fieldTypes: ['TEXT_INPUT'],stageNames: ['SNOw'],teamkey: 'agxdsfsdfsdf9nYWVyEQsSBFRlYW0YgICI_fG-9QsM'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
requestpush.ContentType = "application/x-www-form-urlencoded";
requestpush.ContentLength = byteArray.Length;
//// Get the request stream.
Stream dataStream = requestpush.GetRequestStream();
//// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
//// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = requestpush.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
// The using block ensures the stream is automatically closed.
using (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);
}
// Close the response.
response.Close();
}
catch (Exception e)
{
e.Message.ToString();
}

The remote server returned an error: (405) Method Not Allowed in expedia api call

string url = "https://book.api.ean.com/ean-services/rs/hotel/v3/avail?cid=55505&minorRev=30&apiKey=bsm4nqpcawnppkpwjkej2rfq&locale=en_US&currencyCode=INR&xml=%3CHotelRoomAvailabilityRequest%3E%0A%20%20%20%20%3ChotelId%3E106347%3C%2FhotelId%3E%0A%20%20%20%20%3CarrivalDate%3E9%2F29%2F2015%3C%2FarrivalDate%3E%0A%20%20%20%20%3CdepartureDate%3E10%2F1%2F2015%3C%2FdepartureDate%3E%0A%20%20%20%20%3CincludeDetails%3Etrue%3C%2FincludeDetails%3E%0A%20%20%20%20%3CRoomGroup%3E%0A%20%20%20%20%20%20%20%20%3CRoom%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%0A%20%20%20%20%20%20%20%20%3C%2FRoom%3E%0A%20%20%20%20%3C%2FRoomGroup%3E%0A%3C%2FHotelRoomAvailabilityRequest%3E";
string xmlpath = url;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(xmlpath);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = xmlpath;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/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();
// Get the response.
WebResponse response = request.GetResponse();
Your server requires a GET not POST. Below code works
var url = "https://book.api.ean.com/ean-services/rs/hotel/v3/avail?cid=55505&minorRev=30&apiKey=bsm4nqpcawnppkpwjkej2rfq&locale=en_US&currencyCode=INR&xml=%3CHotelRoomAvailabilityRequest%3E%0A%20%20%20%20%3ChotelId%3E106347%3C%2FhotelId%3E%0A%20%20%20%20%3CarrivalDate%3E9%2F29%2F2015%3C%2FarrivalDate%3E%0A%20%20%20%20%3CdepartureDate%3E10%2F1%2F2015%3C%2FdepartureDate%3E%0A%20%20%20%20%3CincludeDetails%3Etrue%3C%2FincludeDetails%3E%0A%20%20%20%20%3CRoomGroup%3E%0A%20%20%20%20%20%20%20%20%3CRoom%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%0A%20%20%20%20%20%20%20%20%3C%2FRoom%3E%0A%20%20%20%20%3C%2FRoomGroup%3E%0A%3C%2FHotelRoomAvailabilityRequest%3E";
using (var wc = new WebClient())
{
wc.Headers.Add("Accept", "application/xml");
var str = wc.DownloadString(url);
}
if you want the result as json instead of xml, just comment out the line
wc.Headers.Add("Accept", "application/xml");

Web Page Posting and Capturing Response using C#

I have a webpage :http://180.92.171.80/ffs/data-flow-list-based/. After Filling Basin Name and River Name from Drop-down Menu, Station Names are appeared in Flood Forecasting Sites, when I select any of them, it automatically redirect to return that station's information. I need to save that information(Name, Date and present Water Level) on regular basis obviously with C#.
I have some knowledge in C#. I have tried some codes on Webpage posting and Name Value Collection but yet not successful.
Codes are:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");
request.Method = "POST";
formContent = "FormValue1=" + someValue +
"&FormValue2=" + someValue2 +
"&FormValue=" + someValue2;
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
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);
string responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
//You may need HttpUtility.HtmlDecode depending on the response
reader.Close();
dataStream.Close();
response.Close();
Another Code:
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
Can anyone help me in this regard?? It will be a great help for me.
Thanks in advance.
You can also read data through Jquery by their div or span value

WebClient in .NET Compact Framework 2.0

I've a CF 2.0 project where I need to implement something as below:
var myList = new List<MyItem>() { item1, item2 };
using (var webclient = new WebClient())
{
webclient.Headers["Content-type"] = "application/json";
webclient.Encoding = Encoding.UTF8;
var data = JsonConvert.SerializeObject(myList);
var response = webclient.UploadString("http://111.111.111.111:8762/MyService/FetchData", "POST", data);
var myItems = JsonConvert.DeserializeObject(response, typeof(List<MyItem>));
}
I Cannot find System.Net.WebClient in CF 2.0
The example on this page
is a good one for what I was looking for.
public void Test()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/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 ();
// 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.
reader.Close();
dataStream.Close();
response.Close();
}

Remote Server returns error 401 Unauthorized Webexception (POST)

I'm trying to solve an issue that I Mostly (70%) have (30% is succesfull).
I trying to do a webrequest (POST) with the following code:
private string HttpWebRequest(string busStopCode)
{
//XML input
string xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><Siri version='1.0' xmlns='http://www.siri.org.uk/'><ServiceRequest> <RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp><RequestorRef><username></RequestorRef><StopMonitoringRequest version='1.0'> <RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp><MessageIdentifier>12345</MessageIdentifier><MonitoringRef>"+busStopCode+"</MonitoringRef></StopMonitoringRequest></ServiceRequest></Siri>";
string responseFromServer = null;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://<username>:<username>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultNetworkCredentials;
// Create POST data and convert it to a byte array.
string postData = xml;
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.
WebResponse response = null;
while (response == null)
{
try
{
response = request.GetResponse();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription + " Completed");
// 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.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
When I call this function I get mostly a messagebox of my exception with:
"System.Net.WebException: The remote Server returned an error(401) not authorized with System.Net.Http.Webrequest.GetResponse() with WindowsFormApplication1.Form1.HttpWebRequest(string BusstopCode) in <my pathfile>...."
What I'm doing wrong?
I already tried several solutions from previous threads but without success...
Thanks!

Categories

Resources