I'm trying to submit an HTML form through C# using the code below in the following WebPage:
http://liga.record.xl.pt/User/Login.aspx
I can't enter the page. Is that because it uses javascript to login?
private String readHtmlPage(string url)
{
String email = "email";
String password = "password";
String result = "";
String strPost = "email=" + email + "&password=" + password;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
Related
I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
So I'm making a small application for a vbulleting site but need to authenticate the user when he opens my application, I have code to send login request, but I am unsure how to actually check if the login was successful.
This is what I have so far:
public string Login(string username, string password)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
writer.Write(values);
}
HttpWebResponse c = (HttpWebResponse)req.GetResponse();
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
if (c.StatusCode != HttpStatusCode.OK)
return "FAILED_CONNECTION";
return cookie;
}
But how can I check if the authentication was successful?
For other people that may have the same problem, I completely forgot about checking the respone stream for a login successful message, so below is the full code.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
req.AllowAutoRedirect = true;
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
writer.Write(values);
writer.Close();
req.Timeout = 5000;
HttpWebResponse c;
try {
c = (HttpWebResponse)req.GetResponse(); // da response
} catch(Exception e)
{
MessageBox.Show(e.Message, "Web Exception");
return "WebException";
}
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
Stream resp = c.GetResponseStream();
StreamReader reader = new StreamReader(resp, Encoding.GetEncoding(c.CharacterSet));
string response = reader.ReadToEnd();
reader.Close();
reader.Dispose();
if (response.Contains("Thank you for logging in, " + username))
{
c.Dispose();
return cookie;
}
else
return "FAILED_AUTH";
I have generic handler which return me XML in string. How I should call him?
int userid = 1;
string xmlString = string.Format("~/XMLHandler.ashx?userId={0}", userid); // here I need returned string from handler
System.IO.StreamWriter file = new System.IO.StreamWriter("e:\\vypujcky.xml");
file.WriteLine(xmlString);
file.Close();
You can use System.Net.WebClient.DownloadString() to download the resource:
int userid = 1;
Uri resourceUri = new Uri(new Uri(Request.Url.Host), string.Format("XMLHandler.ashx?userId={0}", userid));
System.Net.WebClient webClient = new System.Net.WebClient();
string xmlString = webClient.DownloadString(resourceUri);
// rest of the code is the same
like this
int userid = 1;
string xmlString = string.Format("~/XMLHandler.ashx?userId={0}", userid);
WebRequest req = WebRequest.Create(Server.MapPath("~\")+xmlString);
req.Proxy = null;
req.Method = "POST";
string responseFromServer="";
try
{
WebResponse response = req.GetResponse();
Stream dataStream = response.GetResponseStream();
var statusCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
using(System.IO.StreamWriter file = new System.IO.StreamWriter("e:\\vypujcky.xml"))
{
file.WriteLine(responseFromServer);
}
}
catch (WebException ex)
{
}
I am reading source of the following url but the title is coming as bunch of ?? marks, how do I convert it to actual language that the web page is presenting.
http://support.microsoft.com/common/survey.aspx?scid=sw;ja;3703&showpage=1
private string[] getTitleNewUrl()
{
string url = #"http://support.microsoft.com/common/survey.aspx?scid=sw;ja;3703&showpage=1";
string[] titleNewUrl = new string[2];
var navigatedUrl = string.Empty;
string title = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
navigatedUrl = response.ResponseUri.ToString(); **//this returns [http://support.microsoft.com/default.aspx?scid=gp;en-us;fmserror][1]**
StreamReader sr = new StreamReader(response.GetResponseStream());
var htmlSource = sr.ReadToEnd();
Match m = Regex.Match(htmlSource, #"<title>\s*(.+?)\s*</title>");
if (m.Success)
{
title = m.Groups[1].Value;
}
titleNewUrl[0] = title;
titleNewUrl[1] = navigatedUrl;
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid URL: " + navigatedUrl + " Error: " + ex.Message);
}
return titleNewUrl;
}
Thanks
Here is the answer
public string GetResponseStream(string sURL)
{
string strWebPage = "";
// create request
System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(sURL);
// get response
System.Net.HttpWebResponse objResponse;
objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
// get correct charset and encoding from the server's header
string Charset = objResponse.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
// read response
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream(), encoding))
{
strWebPage = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return strWebPage;
}
I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}