Sending data to php from windows phone - c#

I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.

I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}

First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.

Related

POST or Get Request with Json response in C# windows Form App

I made an API in server side with PHP + Laravel framework which accept both GET & Post requests with some special parameters.
It's address is : http://beresun.ir/API/Orders/0
and it gets these parameters :
token > string ,
restaurant_id > integer ,
admin_id > integer ,
token_id > integer .
if we send a request with GET method with these parameters, for example it will be :
http://beresun.ir/API/Orders/0?token=2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP&restaurant_id=1&admin_id=2&token_id=40 which returns a json data , you can click on the link to see the results .
the response json data includes some information about customers and it's products.
now I want to make a windows application for this service with C# and request data from this API with POST or GET methods :
I want to use this API to get Json data from Web server and save them in my Windows application , So I created two functions in one of my Form Classes :
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public partial class MainActivity : Form
{
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
private void SendWebrequest_Get_Method()
{
try
{
String postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/0?" + postData);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
String json_text = sr.ReadToEnd();
dynamic stuff = JsonConvert.DeserializeObject(json_text);
if (stuff.error != null)
{
MessageBox.Show("problem with getting data", "Error");
}
else
{
MessageBox.Show(json_text, "success");
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
private void SendWebrequest_POST_Method()
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/5");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
// Create POST data and convert it to a byte array.
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
// 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.
MessageBox.Show(((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.
MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
}
Now Here is the problem , when I test the API it works fine , but when I request data from my application , it returns error and not working .
Can anyone explain me how I should request data from this API , to get data , I searched a lot , and I used many different methods , but none of them worked for me . maybe because this API returns very much Json data or maybe request timeout happen. I don't know , I couldn't find the problem . So I asked it Here.
I don't know what I should do .
Thanks
Oki so i run your code :
private string TestURL = "http://beresun.ir/API/";
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
public async Task<string> test()
{
try
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(TestURL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpResponseMessage responce = await Client.GetAsync("Orders/0?" + postData);
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
// !
return Json;
}
else
{
// deal with error or here ...
return null;
}
}
}
catch (Exception e)
{
return null;
}
}
and its working am getting the json file ,, i think your mistake is in postData is string Not String ! a simple type can amazing harm !
try this:
private string URL = "Your Base domain URL";
public async Task<YourModel> getRequest()
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(URL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responce = await Client.GetAsync("Your Method or the API you callig");
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
var Items= JsonConvert.DeserializeObject<YourModel>(Json);
// now use you have the date on Items !
return Items;
}
else
{
// deal with error or here ...
return null;
}
}
}

why my http post method is not accepting xml characters?

here is the function:
private void button6_Click(object sender, EventArgs e1)
{
string requestText = string.Format("strXMLData={0}", System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e));
string data = "strXMLData=%3c&strXMLFileName=text1.xml"; //Working I am //getting in service mathod <
string data = "strXMLData=%3e&strXMLFileName=text1.xml"; //Working I am getting in service mathod >
//string data = "strXMLData=%3c%3e&strXMLFileName=text1.xml"; //this is also working,I am getting in service mathod
//string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "multipart/form-data";
request.ContentLength = dataStream.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
var reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream());
string dataReturn = reader.ReadToEnd();
}
in above code I have written 3 cases from which two are working and 3rd case
string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
is not working can you explain why it is not passing xml string, I am trying to pass
<tag1>
value
</tag1>
As we cannot pass xml without encoding so I encoded this string using
string requestText = string.Format( System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e)); //which returns %3ctag1%3etext%3c%2ftag1%3e
can you explain how to pass xml string..?
without getting error 500
here is web service method
[WebMethod]
public string ReceiveXMLByContent(string strXMLData, string strXMLFileName)
{
string b = System.Web.HttpUtility.UrlDecode(strXMLData);
return "worked";
}
The problem always lies in the following lines
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "multipart/form-data";
Make sure the request.ContentType is especially proper, like in this syntax:
request.ContentType = "text/xml; charset=\"utf-8\"; action=\"HeaderName\";";
Make sure you use try and catch method like this:
private void button6_Click(object sender, EventArgs e1)
{
string GetHttpPost = string.Empty;
GetHttpPost = CallHTTPPostMethod();
}
public string CallHTTPPostMethod()
{
try
{
//Your code
return YourResponseXMLInStringFormat;
}
catch(Exception wex)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return pageContent;
}
}

C# PHP communication

I'm writing an app that will authenticate user from a MySQL database.
I have written it in Java (android) but am now porting to Windows phone.
the PHP file uses $get and then echoes the response:
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$query_search = "select * from users where user = '".$username."'";
//$query_search = "select * from users where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
} else {
echo "User Found";
}
How can I pass the username variable to PHP and then receive the result?
YOUR CODE IS VULNERABLE TO SQL-INJECTION METHOD USE PDO/MYSQLi to AVOID THIS
Create loaded event handler:
using System;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("Your php page url");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),myRequest);
}
creating "POST" data stream:
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "username=value";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
receive response:
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Debug.WriteLine(result);
}
}
use a in-linky stuff like I have a script in my server and you just write: "example.com/save.php?username=textbox1.text&score=points"

Set request properties in Asynchronous web request failed. C#

private void LoginButton_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(DeleResponse), request);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the method which called to on button click event
private void DeleResponse(IAsyncResult result)
{
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
some process here:
}
else if( FAILKEYWORDCHECK HERE)
{
login page process here;
}
}
The problem is when I check this with fiddler I can see only following header properties.
Connection: Keep-Alive;
Host: www.example.com
What would be the reason that I can't set properties in the request header?
Edit: Added synchronous request method which I already achieved without any errors.
private void LoginButton_Click(object sender, EventArgs e)
{
try
{
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
response = (HttpWebResponse)request.GetResponse();
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
MessageBox.Show("Logged in Successfully");
foreach (Cookie cookieReader in response.Cookies)
{
authCookie.Add(cookieReader);
}
Success method continues..
}
else if (loginValidateString.Contains(failedLogKeyword))
{
Failed process
}
}
catch
{
Catchblock
}
}
Means, I just know how to set properties for normal requests.
You're trying to set properties of the request when the response is available. You need to set the request properties before you make the request to the server - so you should be setting them in LoginButton_Click, not in the response handling code. Likewise you can't use GetRequestStream in a callback for BeginGetResponse. Roughly speaking, you want:
In the initial event handler:
Create the request
Set simple properties
Call BeginGetRequestStream
In the callback handler for BeginGetRequestStream
Write out the body data
Call BeginGetResponse
In the callback handler for BeginGetResponse
Handle the response data
Alternatively, unless you have to use the asynchronous calls, you could just create a separate thread and use the synchronous versions instead. Until the language support in C# 5, that would be simpler.

Can't Login to cPanel with C# WebRequest

I am struggling to develop a C# class to login to cPanel on a web host (Hostgator).
In PHP it is quite easy using the Curl extension as follows:
$url = "http://mysite.com:2082/";
$c = curl_init($url);
curl_setopt($c, CURLOPT_USERPWD, 'user:password');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
if ($result === false)
$result = curl_error($c);
curl_close($c);
file_put_contents('log.txt', $result);
//print_r($result);
Now here is my C# class with the various attempts to make it work commented out:
class HTTPHandler
{
public static string Connect (string url, string userName, string password)
{
string result;
try
{
// An initial # symbol in the password must be escaped
if (password.Length > 0)
if (password[0] == '#')
password = "\\" + password;
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(userName, password);
/*
var credCache = new CredentialCache();
credCache.Add(new Uri(url), "Basic",
new NetworkCredential(userName, password));
request.Credentials = credCache;
*/
//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
/*
// Create POST data and convert it to a byte array.
string postData = string.Format("user={0}&pass={1}", userName, password);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
*/
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Display the content.
result = string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
result = string.Format("There was an error:\n{0}", e.Message);
}
return result;
}
}
}
But I keep getting an error 401 (Unauthorized) at the GetResponse stage.
When I compare the $_SERVER vars in my local host test page between the PHP and C# submissions, I get the same data apart from the sender port being a bit different. The crucial PHP_AUTH_USER and PHP_AUTH_PW are the same.
My OS is Windows 7 64 bit and I am using Visual C# 2010.
I guess the solution is really simple, but so far I am baffled. But a relative newbie to C#. I hope somebody can help.
You don't really need to set PreAuthenticate, just let the request figure it out. Also I would suggest using HttpWebRequest instead of WebRequest. The main difference is that you can set CookieContainer property to enable cookies. This is a bit confusing since by default it will have cookies disabled and all you need to do is to set it to new CookieContainer(); to enable cookies for your request.
This matters because of the redirects that happen during authentication and the auth cookie that records the fact that you successfully authenticated.
Also a coding style note: please make sure to wrap all the IDisposables (such as response, stream and reader) in the using() statement.
Also I am unclear why are you escaping # in the password. Request should take care of all your encoding needs automagically.
Complete sample code:
var request = WebRequest.CreateHttp(url);
request.Credentials = new NetworkCredential(username, password);
request.CookieContainer = new CookieContainer(); // needed to enable cookies
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
return string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
edit: Sorry for all the edits. I was writing code by memory and was struggling a bit with getting the encoding part right.
This is using System.Web where I had to set the project properties to use the full .NET Framework 4 to gain access to this assembly for the HttpUtility and add a reference to System.Web in References.
I didn't test all the overloaded methods but the main thing is the cPanel connection where the authentication credentials are added to the http header when a userName is present.
Also, for cPanel I needed to set request.AllowAutoRedirect = false; so that I control page by page access since I didn't manage to capture cookies.
Here is the code for the HTTP Helper Class that I came up with:
class HTTPHandler
{
// Some default settings
const string UserAgent = "Bot"; // Change this to something more meaningful
const int TimeOut = 1000; // Time out in ms
// Basic connection
public static string Connect(string url)
{
return Connect(url, "", "", UserAgent, "", TimeOut);
}
// Connect with post data passed as a key : value pair dictionary
public static string Connect(string url, Dictionary<string, string> args)
{
return Connect(url, "", "", UserAgent, ToQueryString(args), TimeOut);
}
// Connect with a custom user agent specified
public static string Connect(string url, string userAgent)
{
return Connect(url, "", "", userAgent, "", TimeOut);
}
public static string Connect(string url, string userName, string password, string userAgent, string postData, int timeOut)
{
string result;
try
{
// Create a request for the URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (userAgent == null)
userAgent = UserAgent;
request.UserAgent = userAgent;
request.Timeout = timeOut;
if (userName.Length > 0)
{
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
request.AllowAutoRedirect = false;
}
if (postData.Length > 0)
{
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
result = string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
}
}
}
catch (Exception e)
{
result = string.Format("There was an error:\n{0}", e.Message);
}
return result;
}
public static string ToQueryString(Dictionary<string, string> args)
{
List<string> encodedData = new List<string>();
foreach (KeyValuePair<string, string> pair in args)
{
encodedData.Add(HttpUtility.UrlEncode(pair.Key) + "=" + HttpUtility.UrlEncode(pair.Value));
}
return String.Join("&", encodedData.ToArray());
}
}

Categories