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();
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;
}
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'm trying to get some data back from rest WS in C# but I'm getting this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
This is the code I'm trying to use:
var json = new JavaScriptSerializer().Serialize(order);
string jsonResponseToString = "";
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://myurl.com");
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(json);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream str = response.GetResponseStream();
var sr = new StreamReader(str, encoding);
jsonResponseToString = sr.ReadToEnd();
var result = new OrderResult();
result = new JavaScriptSerializer().Deserialize<OrderResult>(jsonResponseToString);
if (str != null)
{
str.Flush();
str.Close();
}
}
}
catch (WebException ex)
{
//
}
The error is happening on this line:
using (var response = (HttpWebResponse)request.GetResponse())
How can I solve this, am I doing something wrong?
As the error is trying to tell you, you need to write your bytes to the request before you can send it.
Call GetRequestStream() and write your bytes.
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}
This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
I am trying to make a json call using C#. I made a stab at creating a call, but it did not work:
public bool SendAnSMSMessage(string message)
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
request.ContentType = "application/json";
string json = "{ \"method\": \"send\", "+
" \"params\": [ "+
" \"IPutAGuidHere\", "+
" \"msg#MyCompany.com\", "+
" \"MyTenDigitNumberWasHere\", "+
" \""+message+"\" " +
" ] "+
"}";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
return true;
}
Any advice on how to make this work would be appreciated.
In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"msg#MyCompany.com\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.
just continuing what #Mulki made with his code
public string WebRequestinJson(string url, string postData)
{
string ret = string.Empty;
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
ret = reader.ReadToEnd();
return ret;
}
Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
#params = new string[]{
"IPutAGuidHere",
"msg#MyCompany.com",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json
Json(someDictionaryObj, JsonRequestBehavior.AllowGet);
Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5
as for your web request...it seems ok at first glance..
I would use something like this..
public void WebRequestinJson(string url, string postData)
{
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
}
May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.
Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this.
Link 1 and Link 2
Code that works(unit tested)
//Get Example
var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var username = "usernameForYourApi";
var password = "passwordForYourApi";
var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
}
//Post Example
var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequestPost.ContentType = "application/json";
httpWebRequestPost.Method = "POST";
bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
//POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
//json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
// fill File model with some test data
CSharpComplexClass fileModel = new CSharpComplexClass();
fileModel.CarrierID = 2;
fileModel.InvoiceFileDate = DateTime.Now;
fileModel.EntryMethodID = EntryMethod.Manual;
fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
string json = new JavaScriptSerializer().Serialize(fileModel);
Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
httpWebRequestPost.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = httpWebRequestPost.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 = httpWebRequestPost.GetResponse();
// Display the status.
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
// 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();
Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);
References in my test script task inside BIDS 2008(having SP1 and 3.5 framework)