What is the alternative to Jquery post in asp.net C#
var scrapyd_url = 'http://www.domain.com/';
var project_name = 'xxxx';
var spider_name = 'yyy';
$.post(scrapyd_url + 'schedule.json', {
project: project_name,
spider: spider_name
});
I think you will like webrequest and webresponse class amde for this purpose only # http://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx
An example (Copied)
public string SendPost(string url, string postData)
{
string webpageContent = string.Empty;
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw;
}
return webpageContent;
}
Related
I am getting a error at this line var json = JsonConvert.SerializeObject(model); I am passing in a HttpPostedFileBase which I am trying to send to a API.
Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'."}
public string UploadToFileManager(HttpPostedFileBase file)
{
var url = string.Format("Common/UploadToFileManager");
var result = ApiHelpers.Post<HttpPostedFileBase> ("POST", url, file);
//return Json(result, JsonRequestBehavior.AllowGet);
return "";
}
public static T Post<T>(string httpMethod, string url, object model)
{
try
{
var fullUrl = cmsApiUrl + url;
var json = JsonConvert.SerializeObject(model);
Stream dataStream = null;
WebRequest Webrequest;
Webrequest = WebRequest.Create(fullUrl);
Webrequest.ContentType = "application/json";
Webrequest.Method = WebRequestMethods.Http.Post;
Webrequest.PreAuthenticate = true;
Webrequest.Headers.Add("Authorization", "Bearer " + cmsApiKey);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
Webrequest.ContentLength = byteArray.Length;
dataStream = Webrequest.GetRequestStream();
using (dataStream = Webrequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = Webrequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
response.Close();
T result = JsonConvert.DeserializeObject<T>(output.ToString());
return result;
}
catch (Exception e)
{
T result = JsonConvert.DeserializeObject<T>("");
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
return result;
}
While debugging this part of code, i am getting
The SSL connection could not be established
Can anybody provide a solution?
WebRequest wr = WebRequest.Create(URL);
wr.Method = "DELETE";
using (WebResponse objResponse = wr.GetResponse())
{
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
string Res = sr.ReadToEnd();
sr.Close();
}
objResponse.Close();
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = data.Length;
request.ServerCertificateValidationCallback = (sender, cert, chain, error) => { return true; };
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(data);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
return responseReader.ReadToEnd();
}
}
catch (Exception e)
{
return e.Message;
}
I'm trying to connect Django API with c # but when I connect I face a problem in C#.
Django here I use as a server API and C# as a client.
Errors in C# are "CSRF is missing or incorrect".
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Net.Http;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
private static string json;
public static string url { get; private set; }
static void Main(string[] args)
{
/*
try
{
CookieContainer container = new CookieContainer();
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/api/");
request1.Proxy = null;
request1.CookieContainer = container;
using (HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response1.Cookies)
{
//Console.WriteLine(response.IsSuccessStatusCode);
var csrf = cookie1.Value;
Console.WriteLine(csrf);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response1.StatusCode);
//PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
catch (WebException e)
{
Console.WriteLine(e.Status);
}
/* HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/");
request.CookieContainer = Cookie; // use the global cookie variable
string postData = "100";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();*/
WebClient csrfmiddlewaretoken = new WebClient();
CookieContainer cookieJar = new CookieContainer();
var request1 = (HttpWebRequest)HttpWebRequest.Create("http://localhost/api/");
request1.CookieContainer = cookieJar;
var response1 = request1.GetResponse();
string baseSiteString = csrfmiddlewaretoken.DownloadString("http://localhost/api/");
// string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
// wc.Headers.Add("X-CSRF-Token", csrfToken);
csrfmiddlewaretoken.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (HttpWebResponse response2 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response2.Cookies)
{
//string cookie = csrfmiddlewaretoken.ResponseHeaders[HttpResponseHeader.SetCookie];//(response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie];
Console.WriteLine(baseSiteString);
//Console.WriteLine("CSRF Token: {0}", csrfToken);
//Console.WriteLine("Cookie: {0}", cookie);
//
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
//wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
var csrf1 = cookie1.Value;
string ARG1 = ("100");
string ARG2 = ("5");
string ARG = ("ARG");
string csrfmiddlewaretoken1 =cookie1.Name +"="+cookie1.Value;
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.Cookie, csrfmiddlewaretoken1);
//string csrf = string.Join(cookie, ARG1, ARG2);
//string dataString =cookie;
// string dataString = #"{""user"":{""email"":"""+uEmail+#""",""password"":"""+uPassword+#"""}}";
string dataString = "{\"ARG1\": \"100\", \"ARG2\": \"5\"}";
// string dataString = "csrftokenmiddlewaretoken="+csrfmiddlewaretoken;
//dataString += "&ARG1=10";
//dataString += "&ARG2=10";
byte[] dataBytes = Encoding.ASCII.GetBytes(dataString);
//byte[] respon2 = csrfmiddlewaretoken.DownloadData(new Uri("http://localhost/api/statusfunction/"));
WebRequest request = WebRequest.Create("http://localhost/api/statusfunction/?ARG");
// 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);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
byte[] responseBytes = csrfmiddlewaretoken.UploadData(new Uri("http://localhost/api/multiplyfunction/"), "POST", dataBytes);
string responseString = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responseString);
// byte[] res = csrfmiddlewaretoken.UploadFile("http://localhost/api/multiplyfunction/", #"ARG1:100");
// Console.WriteLine(result);
Console.WriteLine("value=" + cookie1.Value);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response2.StatusCode);
// PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
}
}
Do you accept POST requests in your Django view? If yes, you should use #csrf_exempt decorator for the view that handles POST requests. The other option is to provide CSRF token from C# side.
How can I retrieve campaign's placements from AdWords through api(.net)?
I'd seen this piece of code, but I can't do something similar via c#.
Also I try to get links through report PLACEMENT_PERFORMANCE_REPORT, but I can't.
public static string GetReport(AdWordsUser user, string customerId)
{
string postData = string.Format("__rdxml={0}", System.Web.HttpUtility.UrlEncode(#"<reportDefinition xmlns=""https://adwords.google.com/api/adwords/cm/v201506"">
<selector>
<fields>CampaignId</fields>
<fields>Impressions</fields>
<fields>Clicks</fields>
<fields>Cost</fields>
<fields>FinalUrls</fields>
<predicates>
<field>Impressions</field>
<operator>GREATER_THAN</operator>
<values>0</values>
</predicates>
</selector>
<reportName>Custom Campaign Performance Report</reportName>
<reportType>PLACEMENT_PERFORMANCE_REPORT</reportType>
<dateRangeType>ALL_TIME</dateRangeType>
<downloadFormat>XML</downloadFormat>
</reportDefinition>"));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://adwords.google.com/api/adwords/reportdownload/v201506");
request.Headers.Add("Authorization", "Bearer " + user.OAuthProvider.AccessToken);
request.Headers.Add("developerToken", "MyToken");
request.Headers.Add("clientCustomerId", customerId);
request.Headers.Add("skipReportSummary", "true");
request.Headers.Add("skipReportHeader", "true");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
var requestWriter = request.GetRequestStream();
requestWriter.Write(byteArray, 0, byteArray.Length);
requestWriter.Close();
string responseData = "";
try
{
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return "";
}
return responseData;
}
Guyz facing problems with creating a push notification service (for android) using Google C2DM which uses OAuth 2.0 . I am sort of newbie dev , and the deadline is on the head ! Please help !
In the above question there was only one issue . I had lost my cool and was into tremendous pressure. This doesn't work well with intellectual property. So , with a bit of mental peace above simple issue was solved.
Guyz below given is the code for the dummies like me :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using System.Collections;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Configuration;
using System.Web.Script.Serialization;
using PushNotification.Entities;
namespace PushNotification
{
public class AndroidCommunicationService
{
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public string GetAuthenticationCode()
{
string returnUrl = "";
string URL = "https://accounts.google.com/o/oauth2/auth";
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("response_type", "code");
postFieldNameValue.Add("scope", "https://android.apis.google.com/c2dm/send");
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"].ToString());
postFieldNameValue.Add("redirect_uri", "http://localhost:8080/TestServer/test");
postFieldNameValue.Add("state", "profile");
postFieldNameValue.Add("access_type", "offline");
postFieldNameValue.Add("approval_prompt", "auto");
postFieldNameValue.Add("additional_param", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var sr = new StreamReader(Response.GetResponseStream());
// You can do this and return the content on the screen ( I am using MVC )
returnUrl = sr.ReadToEnd();
// Or
returnUrl = Response.RedirectUri.ToString();
}
catch
{
throw ;
}
return returnUrl;
}
public TokenResponse GetNewToken(string Code)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("code", Code);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("redirect_uri", ConfigurationManager.AppSettings["RedirectUrl"]);
postFieldNameValue.Add("grant_type", "authorization_code");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch (WebException wex)
{
var sr = new StreamReader(wex.Response.GetResponseStream());
Exception ex = new WebException(sr.ReadToEnd() + wex.Message);
throw ex;
}
return tokenResponse;
}
public TokenResponse RefreshToken(string RefreshToken)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("refresh_token", RefreshToken);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("grant_type", "refresh_token");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch
{
throw;
}
return tokenResponse;
}
public string SendPushMessage(string RegistrationId, string Message ,string AuthString)
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["PushMessageUrl"]);
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("registration_id", RegistrationId);
postFieldNameValue.Add("collapse_key", "fav_Message");
postFieldNameValue.Add("data.message", Message);
postFieldNameValue.Add("additional_value", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
// This is to be sent as a header and not as a param .
Request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AuthString);
try
{
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return responseLine;
}
catch
{
throw;
}
}
private string GetPostStringFrom(NameValueCollection postFieldNameValue)
{
//throw new NotImplementedException();
List<string> items = new List<string>();
foreach (String name in postFieldNameValue)
items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(postFieldNameValue[name])));
return String.Join("&", items.ToArray());
}
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
}
}
public class TokenResponse
{
public String access_token{ get; set; }
public String expires_in { get; set; }
public String token_type { get; set; }
public String refresh_token { get; set; }
}