I need to use StreamSend API to send email, here is
StreamSend API Reference
I am making web request as post to following URL with proper credentials
https://app.streamsend.com/audiences/2/blasts.xml
StringBuilder sb = new StringBuilder();
sb.Append("https://app.streamsend.com/audiences/2/blasts.xml");
Uri uri = new Uri(sb.ToString());
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.ContentType = "application/xml";
StringBuilder strMail= new StringBuilder();
strMail.Append("<blast> ALL from api..... </blast>");
byte[] data = Encoding.ASCII.GetBytes(strMail.ToString());
Stream input = request.GetRequestStream();
input.Write(data, 0, data.Length);
input.Close();
HttpWebResponse nsResponse = (HttpWebResponse)request.GetResponse();
i am having err# 422 or 500. i would appreciate any help.
A couple of things. First, it looks like you're trying to do a POST request (you're sending data in the request stream). If you really want a POST request, you have to set request.Method = "POST";
Also, if you want an XML response, you need to set the Accept header. According to the documentation you listed, you need: request.Accept = "application/xml";
And you need to add your login id to the request, as well. I'm not sure how that's done. Perhaps in the request.Credentials property like this:
request.Credentials = new NetworkCredential("login_id", "your_key_here");
Finally, there's no reason to use StringBuilder if all you're doing is assigning strings. You can write, for example:
string urlString = "https://app.streamsend.com/audiences/2/blasts.xml"
Uri uri = new Uri(urlString);
or
byte[] data = Encoding.ASCII.GetBytes("<blast> ALL from api..... </blast>");
Related
I have a Post call that takes a string GUID "AA0DB615-D4CB-4466-BC23-0E0083002220"
I am using HTTPWebRequest to send request but I am not sure how to add this along with my Post request. Basically I have not found any method inside the HTTPWebRequest to send a Post that is just a string or a character datatype. Is their anything like request.AddBody.
I have also looked at the GetResponseStream. Can I use this to write to the body as a string or character data type and send the call. I am stuck on this any help would be great
Here's a sample request that sends a plain text GUID in the body using HttpWebRequest, You can set the Content type to "text/plain" if you want to explicitly state that the content type is plain text :
var request = (HttpWebRequest)WebRequest.Create("URL GOES HERE");
request.Method = "POST";
var content = Guid.NewGuid().ToString(); //You should replace this with your GUID
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(content);
request.ContentType = "text/plain";
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
var response = request.GetResponse() as HttpWebResponse;
}
I have a string with 300 rows, there is a way to do it POST?
Here is my code, is currently working on a limited amount of short letters:
WebRequest req = (HttpWebRequest)WebRequest.Create(
"http://thisisurl/test.php?ad=test&f=" + information_data);
req.Method = "POST";
WebResponse res = req.GetResponse();
I'm going to explain your problem right now and go ahead and give you a possible solution at the end.
You are hitting the character limit for url length / query parameter length. IE limits it as low as 2,083.
The data you are providing should be sent in the body of the http request, not the URL parameters.
A Post Request Normally is done in the following format(Code from the link).
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
}
This thread should have enough info if you want to use the WebRequest class instead:
HTTP request with post
I'm executing the following code in order to register a randomized user name and a password for login using live id.
String regUrl = "https://login.live.com/ppsecure/DeviceAddCredential.srf";
WebRequest request = WebRequest.Create(regUrl);
request.ContentType = "application/soap+xml; charset=UTF-8";
request.Method = "POST";
request.Timeout = 60000;
StreamReader reader = new StreamReader(request.GetRequestStream());
String contents = reader.ReadToEnd();
I'm following the code in this article and it's not going quick nor easy. I get the error telling me that stream was not readable.
What am I missing and what can be done about it?
You're trying to read from a request stream, when you should be writing to it. The response stream contains the server's reply.
I would like to know why my asp.net application will not add the header to my post when it is named 'Authorization' but will work fine when I change one character, say "Authorizations". In documentation for other sites they always use the name "Authorization" so I would like to as well and at this point I just want to under stand why.
I have read a few topics about this but have not found any logical reason why.
Here is my code below:
string fileName = "c:\\xyz.xml";
string uri = "http://myserver/Default.aspx";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
byte[] authBytes = Encoding.UTF8.GetBytes("DDSServices:jCole2011".ToCharArray());
req.Headers.Add("Authorization", "BASIC " + Convert.ToBase64String(authBytes) );
req.Headers.Add("test", "test");
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(this.GetTextFromXMLFile(fileName));
req.ContentLength = data.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
req.Headers.Add("Authorization", "BASIC" + Convert.ToBase64String(authBytes));
System.Net.WebResponse response = req.GetResponse();
System.IO.StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
The other annoying this is when i add the watched variable through fiddler it works fine.
I was ran into a question how to add Authentication/Credentials to the headers. I found the solution in the following way.
string _auth = string.Format("{0}:{1}", "myUser","myPwd");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
string _cred = string.Format("{0} {1}", "Basic", _enc);
req.Headers[HttpRequestHeader.Authorization] = _cred;
Which gave me those headers I want (pasted Wireshark descriptions),
Authorization: Basic bXlVc2VyOm15UHdk\r\n
Credentials: myUser:myPwd
For HTTP Basic Authorization, you should be using the Credentials property.
req.Credentials = new NetworkCredential("DDSServices", "jCole2011");
This should do what you want. Rather than setting the Authorization header.
NetworkCredential is a good solution but the site you are calling has to handle an unauthorized with a 401 AND a WWW-Authenticate header in the response.
Client:
request.Credentials = new CredentialCache {{aUri, "Basic", new NetworkCredential(aUserName, aPassword)}};
Server:
Response.ClearContent();
Response.StatusCode = 401;
Response.AddHeader("WWW-Authenticate", "Basic");
Response.End();
This will result in 2 hits to the server. The initial call will go to the server without credentials. When the server responds with a 401 AND the WWW-Authenticate header (with the type of authentication required), the request will be resent with the credentials in the request.
I have done this code to login,to retrieve and show a webpage :
// login info array
string postData = "user_name=tler";
postData += "&user_password=lodvader";
byte[] data = Encoding.ASCII.GetBytes(postData);
// web request
WebRequest req = WebRequest.Create("http://www.lol.com/login.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// stream response to string
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
string responseString = reader.ReadToEnd();
// retrieve text within title
Regex rx = new Regex(#"(?<=<title>).+?(?=</title>)");
var variable = rx.Matches(responseString);
// output
Console.WriteLine(variable[0]);
Console.ReadLine();
But, the following page after login is an html redirect like :
<meta http-equiv="refresh" content="3; URL="bb.php">
How to follow this link and retrieve next page ?
Just send a new WebRequest to the bb.php file. Make sure that you use the same CookieContainer since I presume that login.php uses cookie-based sessions to remember you. Check out the HttpWebRequest.CookieContainer property. This requires you to cast your WebRequest to a HttpWebRequest.
Added: (Couldn't write example code in the comment.)
I'm just making code up without proofing now...
var cookies = new CookieContainer();
var firstReq = (HttpWebRequest)WebRequest.Create(".../login.php");
firstReq.CookieContainer = cookies;
var secondReq = (HttpWebRequest)WebRequest.Create(".../bb.php");
secondReq.CookieContainer = cookies
I have found the time to finish it, here the response ( i tried to be as clear as possible ) :
// Cookie for our session
var cookieContainer = new CookieContainer();
// Encode post variables
ASCIIEncoding encoding=new ASCIIEncoding();
byte[] loginDataBytes = encoding.GetBytes("user_name=belaz&user_password=123");
// Prepare our login HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://blabla.fr/verify.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.ContentLength = loginDataBytes.Length;
// Write encoded post variable to the stream
Stream newStream = request.GetRequestStream();
newStream.Write(loginDataBytes, 0, loginDataBytes.Length);
newStream.Close();
// Retrieve HttpWebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Link the response cookie to the domain
cookieContainer.Add(new Uri("http://blabla.fr/"),response.Cookies);
// Prepare our navigate HttpWebRequest, and set his cookie.
HttpWebRequest requestProfile = (HttpWebRequest)WebRequest.Create("http://blabla.fr/bb.php");
requestProfile.CookieContainer = cookieContainer;
// Retrieve HttpWebResponse
HttpWebResponse responseProfile = (HttpWebResponse)requestProfile.GetResponse();
// Retrieve stream response and read it to end
Stream st = responseProfile.GetResponseStream();
StreamReader sr = new StreamReader(st);
string buffer = sr.ReadToEnd();
There is a property of HttpWebRequest called AllowAutoRedirects. Set this to true. Also there is a property called MaximumAutomaticRedirections. Set that to some allowable value to make sure all of them are followed.
You can't do it a easy way, since the meta tag is read by the client and executed.
In this case, when you're using HttpWebRequest, the request doesn't care about the functions the text may have.
So you need to do another request to the page in the URL attribute (bb.php).
-
If the server did the redirection you wouldn't have the problem.