I have this HttpWebRequest:
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";
But I need to add a payload to the body of the request like this:
Jlpt = 2
Can someone help and tell me how I can add data to the POST ?
You can do by this
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
but I suggest you use HttpClient rather than HttpWebRequest in this case
if (data != null)
{
request.ContentType = "application/json";
using (var stream = new StreamWriter(request.GetRequestStream()))
{
var serialized = JsonConvert.SerializeObject(data);
stream.Write(serialized);
}
}
else
{
request.ContentLength = 0;
}
where data is any object you want to send
Related
I'm coding a script that goes on a website, adds to cart an item, and checkout.
I manage to add to cart but when I want to checkout it's like nothing is in the cart.
How can I add to cart/ checkout using the same session?
Here is my code:
var request = (HttpWebRequest)WebRequest.Create(url_add_to_cart);
var postData = "utf8=✓";
postData += "style=" + data_style_id;
postData += "size=" + size;
postData += "commit=add to basket";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//checkout----------------
var url_checkout = link_general + "/checkout.json";
var request2 = (HttpWebRequest)WebRequest.Create(url_checkout);
var postData2 = "utf8=✓";
postData2 += "order[billing_name]=toto";
postData2 += "order[email]=toto#gmail.com";
var data2 = Encoding.ASCII.GetBytes(postData2);
request2.Method = "POST";
request2.ContentType = "application/x-www-form-urlencoded";
request2.ContentLength = data2.Length;
using (var stream2 = request2.GetRequestStream())
{
stream2.Write(data2, 0, data2.Length);
}
var response2 = (HttpWebResponse)request2.GetResponse();
var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString2);
When I do the checkout request it doesn't work and get the source corde of the website html home page
Thank you very much for your answers
You need to store request.CookieContainer in local variable and every time you need to send new request set it again
private CookieContainer cookieContainer;
private void SendRequest()
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
if (this.cookieContainer != null)
request.CookieContainer = this.cookieContainer;
else
request.CookieContainer = new CookieContainer();
...
...
...
this.cookieContainer = request.CookieContainer;
}
And add & to end of postData lines
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 and he is broken when I try to cut my custom string like: "to="+value+"&from="+value+"&title="+value+"&message="+value
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
Maybe I need to change Content Type and send jsonString to the server? But if that true, what format I need to use?
You need to URL encode the data.
"to="+value+"&from="+value+"&title="+value+"&message="+value
should be changed to:
"to="+HttpUtility.UrlEncode (value)+"&from="+HttpUtility.UrlEncode(value)+"&title="+HttpUtility.UrlEncode(value)+"&message="+HttpUtility.UrlEncode (value)
I'm trying to login to this website here: https://freebitco.in/
So I set up a web request like so:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=BTCADDRESS&password=PASSWORD";
var data = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length; //1PkhThc9hCXpdvcThtwX3SzbfmTzDFxL1h:bigken <= BTC Login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
MessageBox.Show(responseString);
The messagebox returns to me nothing though, blank. I'm not sure why this is happening so I was hoping someone could shed some light on this? I've also tried using a Web Client, and it gave me the same result. Thank you guys.
EDIT: Here's the Fiddler Raw data: http://pastebin.com/WUEvq6D5
Edit 2: Tried encoding the POST data and now it returns the login page
Updated Code:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=ADDRESS&password=PASS";
var encoded_data = HttpUtility.UrlEncode(postdata);
var data = Encoding.ASCII.GetBytes(encoded_data);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}
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);
}