Excuse any ignorance on my part with this methodology as it is somewhat new to me. I've been reading up on it as much as I can, but haven't been able to solve this yet.
I'm trying to accomplish a SSO with a vendor through an http post. Simple enough. I've done this in the past, but it usually returns a url that I can then redirect the user to. Unfortunately, with this vendor they are returning the entire page, html and all. Is this typical? If so, is my only solution to post this to a new window?
For reference, here's my code so far:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] postBytes = Encoding.UTF8.GetBytes(postString);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream);
var responseString = responseReader.ReadToEnd();
responseReader.Close();
responseStream.Close();
response.Close();
Does everything look normal and ok so far?
It is normal for a POST request to return a new web page. I would think the redirect would be the abnormal case.
You're pretty vague about your app, so I'm not sure how you'll want to get the returned html shown to the user.
You might want to check out the WebClient class which could simplify your code considerably.
using (var client = new WebClient())
{
var resultBytes = client.UploadData(new Uri("http://example.com"), "POST", data);
}
Related
I am currently trying to retrieve a xml response and parse the result from a web service, but I have ran into issues when receiving the response as a stream and using stream reader to read the result and convert the xml response to a string so it can be parsed to get a result later.
When testing I receive an error that there is illegal characters in path, as the stream reader only accepts a file path not the actual xml response object itself. After extensive searching most of the similar posts on here, most people point to either textreaders or xmlreaders but as the HttpWebResponse returns a stream I can't use those. Does anyone have a idea's or pointers to help me overcome this?
I have included a snippet of the code to how I am handling the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string soapResult = responseStream.ReadToEnd();
Here is the code for the request, just in case it helps.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Location);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "application/soap+xml; charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
Thanks
Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//
request.Method = "POST";
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
Stream requestBodyStream = request.GetRequestStream();
requestBodyStream.Write(requestBody, 0, requestBody.Length);
requestBodyStream.Flush();
requestBodyStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.
I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.
My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.
Why is this method not producing any body?
Add 'ContentType' and 'ContentLength' headers to the request instance:
request.ContentType = "application/json"; // Or whatever you want
request.ContentLength = requestBody.Length;
I cannot successfully call an API using C# at the moment. I have attached a screen shot of the call being successfully made with Chrome PostMan although I'm not able to replicate it in C#. He is my attempt so far which fails. The response I get back from the server is included below. Can anyone see what I'm doing wrong?
Many thanks,
James
Code Snippet
const string xml = "<Envelope><Body> <AddRecipient>...";
var req = (HttpWebRequest)WebRequest.Create(ApiUrl);
var requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.Headers.Add("Authorization", "Bearer " + token);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
var requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
var res = (HttpWebResponse)req.GetResponse(); // Call API
var sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
var backstr = sr.ReadToEnd();
sr.Close();
res.Close();
Chrome PostMan
Response back from API
<Envelope><Body><RESULT><SUCCESS>false</SUCCESS></RESULT><Fault><Request/><FaultCode/><FaultString>Server Error</FaultString><detail><error><errorid>50</errorid><module/><class>SP.API</class><method/></error></detail></Fault></Body></Envelope>
Is there any documentation about what error 50 is? Could just be a bad pram? If not I recommend downloading fiddler. You can then properly compare the request from both PostMan and your application to see what the actual difference is.
I am trying to send base64 encoded data through C# WebRequest to php script. Then I receive sent data by file_get_contents("php://input"), when data length is lower than 8 KBs the php code is executed, otherwise it can't be executed. In the other hand php didn't receive the request.
the code C#:
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
// postData is Base64_encoded
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseData = reader.ReadToEnd();
responseData = SecurityUtils.DecryptUrlData(responseData);
reader.Close();
dataStream.Close();
response.Close();
return responseData;
Could any one help?
The below is incorrect (mea culpa). You cannot use enctype=multipart/form-data with php://input. See here
Perhaps you can post your PHP code into your question as well?
Make sure that when you POST from the c# app to your PHP app that you set the enctype to multipart/form-data.
Explanaition
Are you using application/x-www-form-urlencoded or multipart/form-data? There is a good explanation of the differenes here: application/x-www-form-urlencoded or multipart/form-data?
According to the link above, posting data in the application/x-form-urlencoded format will put the body into the URL. Many servers and languages (PHP, Apache) will cut off or throw errors when the URL is greater than 8K. See SO question: What is the maximum length for a URL?
Change the content type for the request
request.ContentType = "text/plain";
Check out php.iniĀ“s post_max_size on the server side
This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the Wikipedia API. I have posted my code below if anyone can help me see my problem.
string pgTitle = txtPageTitle.Text;
Uri address = new Uri("http://en.wikipedia.org/w/api.php");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string action = "query";
string query = pgTitle;
StringBuilder data = new StringBuilder();
data.Append("action=" + HttpUtility.UrlEncode(action));
data.Append("&query=" + HttpUtility.UrlEncode(query));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream.
StreamReader reader = new StreamReader(response.GetResponseStream());
divWikiData.InnerText = reader.ReadToEnd();
}
You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:
http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page
Here's the code:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page");
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
string ResponseText;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ResponseText = reader.ReadToEnd();
}
}
Edit: The other problem he was experiencing on the POST request was, The exception is : The remote server returned an error: (417) Expectation failed. It can be solved by setting:
System.Net.ServicePointManager.Expect100Continue = false;
(This is from: HTTP POST Returns Error: 417 "Expectation Failed.")
I'm currently in the final stages of implementing an C# MediaWiki API which allows the easy scripting of most MediaWiki viewing and editing actions.
The main API is here: http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs and here is an example of the API in use:
var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php");
wiki.login(userName, password);
var page = "Test"; // "Main_Page";
wiki.editPage(page,"Test content2");
var rawWikiText = wiki.raw(page);
var htmlText = wiki.html(page);
return rawWikiText.line().line() + htmlText;
You seem to be pushing the input data on HTTP POST, but it seems you should use HTTP GET.
From the MediaWiki API docs:
The API takes its input through
parameters in the query string. Every
module (and every action=query
submodule) has its own set of
parameters, which is listed in the
documentation and in action=help, and
can be retrieved through
action=paraminfo.
http://www.mediawiki.org/wiki/API:Data_formats