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;
}
Related
I'm trying to post XML from www.domain1.com a controller in www.domain2.com.
Here is my code:
www.domain2.com
[HttpPost]
public ActionResult FetchProductsXML()
{
Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
var products = _productService.SearchProducts(showHidden: false);
var xml = _exportManager.ExportProductsToXml(products);
return this.Content(xml, "text/xml");
}
Then in www.domain1.com I am posting as follows..
private string getProductLIstXML()
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = "<testXml>test</testXml>";
try
{
byte[] data = encoding.GetBytes(SampleXml);
string url = "http://www.domain2.com/products-xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(SampleXml);
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();
return responseStr;
}
return null;
}
catch (WebException webex)
{
return webex.ToString();
}
}
My Custom Route in RouteProvider class
routes.MapLocalizedRoute("FetchProductsXML",
"products-xml",
new { controller = "Product", action = "FetchProductsXML" },
new[] { "Nop.Web.Controllers" });
The error I get is
System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.GetResponse()
I've followed what the examples from the following SOQ's
How to POST XML into MVC Controller? (instead of key/value)
HTTP post XML data in C#
After a long night, I realized I had the method in the incorrect class :(
All fixed now.
I need to send email thanks to php script. Sript in the server, I did post request to the server, and got answer. If all is good I get 0, if I get 1, all is bad.
This is my code:
public class MessagePost
{
public string to { get; set; }
public string from { get; set; }
public string title { get; set; }
public string message { get; set; }
}
[HttpPost]
public ActionResult SendMessage(FEEDBACK feedbackModel)
{
try
{
string FromEmail = feedbackModel.sEmail;
string toEmail = "zicise#mail.ru";
string title = "Сообщение с сайта народный комунальщик от " + feedbackModel.vFIO;
string message = feedbackModel.vMessage;
MessagePost MP = new MessagePost();
MP.to = toEmail;
MP.from = FromEmail;
MP.title = title;
MP.message = message;
List<MessagePost> dataMessage = new List<MessagePost>();
dataMessage.Add(MP);
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(dataMessage);
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://projects.pushnovn.com/send_email/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = json;
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 = 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();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
string convertResult = System.Text.Encoding.UTF8.GetString(byteArray);
RootObject r = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
if (r.code == 0)
{
ViewBag.RedirectMessage = r.msg;
return View("~/Views/Home/RedirectPage.cshtml");
}
else
{
ViewBag.RedirectMessage = r.msg;
return View("~/Views/Home/RedirectPage.cshtml");
}
}
catch (Exception exc)
{
ViewBag.RedirectMessage = "Невозможно отправить e-mail - error: " + exc.Message;
return View("~/Views/Home/RedirectPage.cshtml");
}
}
But I always get 1, what's wrong?
E.g. data
to: zicise#mail.ru
from: test#mail.ru
title: Test Title
message: Test message
Okay.So, I did it.But not good what I want. This is my code for send post query to the server:
public static HttpWebResponse PostMethod(string postedData, string postUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
UTF8Encoding encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(postedData);
//request.ContentType = "application/javascript";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "application/json; charset=utf-8";
//request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.ContentLength = bytes.Length;
using (var newStream = request.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
}
return (HttpWebResponse)request.GetResponse();
}
And ActionResult:
[HttpPost]
public ActionResult SendMessage(FEEDBACK feedbackModel)
{
MessageData msgData = new MessageData();
msgData.to = "zicise#mail.ru";
msgData.from = feedbackModel.sEmail;
msgData.title = "Сообщение с сайта наркома от пользователя: " + feedbackModel.vFIO;
msgData.message = feedbackModel.vFIO;
var jsonString = JsonConvert.SerializeObject(msgData);
var response = PostMethod("to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("[{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}]", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod(jsonString, "http://projects.pushnovn.com/send_email/");
if (response != null)
{
var strreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var responseToString = strreader.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(responseToString);
ViewBag.RedirectMessage = r.msg;
}
return View("~/Views/Home/RedirectPage.cshtml");
}
But this code worked only when I send data in format: to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message
But I need to send data from model and get 0 answer. After that PHP script send me email with data. Anyone know, how to convert object in json format name=value&name=value
I have a unique request for me, where I need to send a JSON POST request but read a XML GET. I have tried this below, but I get an error of
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
What do I alter in order for my XML GET to succesful be able to read the response?
public bool PerformPost(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
string strEndpointURL = string.Format("websitegoeshere");
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string strPostData = "";
foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
strPostData += "hs_context=";
HttpWebRequest r = (System.Net.HttpWebRequest)WebRequest.Create(strEndpointURL);
r.Method = "POST";
r.Accept = "application/json";
r.ContentType = "application/x-www-form-urlencoded";
r.ContentLength = strPostData.Length;
r.KeepAlive = false;
Stream datastream = r.GetRequestStream();
WebResponse response = r.GetResponse();
datastream = response.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
string responsefromserver = reader.ReadToEnd();
var xml = System.Xml.Linq.XElement.Parse(responsefromserver);
if (xml.Elements("sid").FirstOrDefault().Value == "1") { return true; }
else
{
var errors = xml.Elements("fail");
foreach (var error in errors.Elements("fail"))
{
strMessage = error.Value;
return false;
}
}
reader.Close();
datastream.Close();
response.Close();
return true;
}
You haven't written the post data to the request stream. You will need to call datastream.Write before you call GetResponse.
For example:
var buffer = Encoding.UTF8.GetBytes(strPostData);
r.ContentLength = buffer.Length;
datastream.Write(buffer, 0, buffer.Length);
datastream.Close();
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;
}
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;
}