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.
Related
I need to Post the XML data to a URL.But I am facing some Error in the (Stream requestStream = request.GetRequestStream()) Line
Errror Image .
I have saved the xml in the file and provided the path for that . I think there is Issue while passing XML Data but when I try to use the same XML in the POSTMan using POSTmethod.I can able to get the response Data.
This is the reference link HTTP post XML data in C#
And here is my code
static void Main(string[] args)
{
string url = "*****************";
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(#"Path of the xml file");
var sw = new StringWriter();
Xdoc.Save(sw);
string result = sw.ToString();
string response = **********.postXMLData(url, result);
Console.WriteLine(response);
Console.ReadLine();
}
public static string postXMLData(string destinationUrl, String requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding=utf-8";
request.ContentLength = bytes.Length;
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
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;
}
I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo ID Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}
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 am trying to post data from PCL project to remote server. Below is my code:
public async Task<bool> SendToken(string deviceToken, string userId)
{
HttpWebRequest request;
string url = "http://192.168.1.171:91/api/updatePushDeviceToken";
request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.Method = "POST";
string postData = string.Format("userId={0};token={1}&deviceType={2}", userId, deviceToken, deviceType);
var data = Encoding.UTF8.GetBytes(postData);
try
{
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}
catch (Exception e)
{
string m = e.Message;
}
return false;
}
private void FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
var responseString = readStream.ReadToEnd();
}
While running above code, below exception was thrown:
System.Net.WebException: The remote server returned an error: (411)
Length Required.
PCL doesn't contain ContentLength property, hence I added Length as below but now I am getting exception as:
try
{
request.Headers[HttpRequestHeader.ContentLength] = "0";
}
catch (Exception e)
{
}
System.ArgumentException: This header must be modified with the
appropiate property. at
System.Net.WebHeaderCollection.CheckRestrictedHeader (System.String
headerName)
Your request is missing of ContentLength property of your post parameters.
var parameters = Encoding.ASCII.GetBytes(qstring);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContentType="application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentLength = parameters.Length;
//Send it
var reqStream = request.GetRequestStream();
reqStream.Write(parameters, 0, parameters.Length);
reqStream.Close();
//read it
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string responseHtml = sr.ReadToEnd().Trim();
And please use querystring format to post data, for example : "userId={0}&token={1}&..."
I am working on consuming a REST API and I am using basic authentication where password is encoded to Base64 as follows
private XmlDocument sendXMLRequest(string requestXml)
{
string destinationUrl = "https://serviceapi.testgroup.com/testtp/query";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("API_TEST_NR:Testnol1$"));
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.Method = "POST";
request.ContentLength = bytes.Length;
//request.Connection = "keep-alive";
request.ContentType = "text/xml";
request.KeepAlive = true;
request.Timeout = 2000;
request.MediaType = "text/xml";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
Stream responseStream;
using (response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
XmlReader reader = new XmlTextReader(responseStream);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
try { reader.Close(); }
catch { }
try { responseStream.Close(); }
catch { }
try { response.Close(); }
catch { }
return xmlDoc;
}
}
try { response.Close(); }
catch { }
return null;
}
I'm kind of new to working on Web Api's and I know that the API responds with an access x-token after successful authorization based on the API documentaion and I am not sure how to access or capture it from the HTTP headers.
May I know a good way I can achieve this?
This is easier than I thought just capturing with its name.
string xtoken= response.Headers["custom-header"];
Console.WriteLine(xtoken);
Try this as below, represents, Request Data Using the WebRequest Class.In most cases, the WebRequest class is sufficient to receive data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference.
private XmlDocument GetRootLevelServiceDocument(
string serviceEndPoint, string oAuthToken)
{
XmlDocument xmlDoc = new XmlDocument();
HttpWebRequest request = CreateHttpRequest(serviceEndPoint,
oAuthToken);
using (HttpWebResponse response =
(HttpWebResponse)request.GetResponse())
{
using (XmlReader reader =
XmlReader.Create(response.GetResponseStream(),
new XmlReaderSettings() { CloseInput = true }))
{
xmlDoc.Load(reader);
string data = ReadResponse(response);
if (response.StatusCode != HttpStatusCode.OK)
{
LogMsg(string.Format("Error: {0}", data));
LogMsg(string.Format(
"Unexpected status code returned: {0}",
response.StatusCode));
}
}
}
return xmlDoc;
}