I have a webRequest to create. So I am using (httpwebrequest)webrequest.Create("/get").
I need to send some payload/request body to this request.
But stream writer only seems to work with POST request.
How do I achieve that?
You should not attempt to use a get request to post data to a server. Instead, you should use a post request to accomplish this. It is highly recommended that you do not use a webrequest and instead use HttpClient but if for some reason you absolutely must use webrequest like if you're working with legacy code this is the basic method of accomplishing this:
try
{
WebRequest request = WebRequest.Create("http://www.server.example/api/example");
request.Method = "POST";
byte[] package = Encoding.UTF8.GetBytes("package string example");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = package.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(package, 0, package.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
using (dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
//do something with the data retrieved from the server
}
response.Close();
}
catch (Exception ex)
{
//example catch
}
Related
http://i.stack.imgur.com/hDpwl.jpg
I need a code snipped which I can use in a WPF application. It should send a post request to the server and return a JSON. Best would be if its working same as the print screen from chrome add-on postman above. I tried to use uploading form Data with HttpClient and uploading form data with WebRequest and it returned HTML page with an error.
Thanks all
public string PostJson(string url,string json)
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentType = "application/json";
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 responseFromServer = reader.ReadToEnd();
Console.Writeline(string.Format("Request {0} Response Code {1} Resonse Status Description {2} Response From Server {3}",
json, ((HttpWebResponse)response).StatusCode,
((HttpWebResponse)response).StatusDescription, responseFromServer));
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
I've been trying to have a WPF client connecting to a PHP server, logging itself in and fetching 'IsLogged.php' to validate that the client is logged in. However, 'IsLogged.php' always returns that the client isn't authenticated, what am I doing wrong?
Servercode:
"CreateAccount.php"
session_start();
if (isset($_POST['user']))
{
$_SESSION['UserName'] = $_POST['user'];
echo "check";
}
"IsLogged.php"
session_start();
if (isset($_SESSION['UserName']))
{
echo "allowed";
}
else
{
echo "not allowed";
}
Client code:
"Post" method
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
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();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
And finally the window triggering the POST requests.
HttpStatusCode Code;
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)
Why is the server not registering the requests as a session?
The way the server identifies the client (and the corresponding session state) is through cookies.
Basically, in the CreateAccount request, the server attaches a cookie to its response and expects the client to present the cookie on every subsequent request.
If the cookie is not present in a request, the server has no way of identifying the client and treats the request as coming from an unknown source.
Your code does not manage cookies at all, so this is why the C# client always appears to be a new client to the PHP server.
The easiest way to save the cookie received from the server and present it on every new request is to use an instance of CookieContainer and attach it to every request you make.
I didn't try this code, so I'm not 100% sure of the syntax, but here's a starting point:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Request.CookieContainer = cookieContainer; // this line is new
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
I would like to write a class in c# which should send an HTTP request (post) to a PHP file which is on my server in order to retrieve a json object.
This is the code I've got:
public void SendRequest(){
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("url");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
}
Is that what I need? What do you think I should change or improve?
Thank you for your help.
You need to post data and read the response:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;
byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
using (response = (HttpWebResponse)request.GetResponse())
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
sreverResponseText = streamReader.ReadToEnd();
Now what you are looking for is in sreverResponseText, also you can access headers from response.Headers.ToString()
I am currently having a problem.
I am trying to post my data to a PHP document but it does not get the whole value.
Somewhere in the middle it stops posting.
Does anyone know where the problem is located?
The bytearray is 7401 long. That cant be to long rigth?
My code is below:
public string RecieveData(string url, string postData = "")
{
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
NetworkCredential nc = new NetworkCredential("user", "pass");
Stream dataStream;
if (postData != "")
{
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.string postData = "This is a test that posts this string to a Web server.";
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.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
request.Credentials = nc;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(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();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
/*
}
catch (Exception)
{
MessageBox.Show("Er is iets fout gegaan met verbinden");
return "";
}
*/
}
7401 is not too long.
My guess is that the data you are posting are not fully URL-encoded, e.g. one of the characters in the byte array causes the PhP parser to stop. Make sure you are looking at the raw data (e.g. using Wireshark).
I am trying to replicate a Couch database using .NET classes instead of a curl command line. I have never used WebRequest or Httpwebrequest before, but I am attempting to use them to make a post request with the script below.
Here is the JSON script for couchdb replication(I know this works):
{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } }
The above script is put into a text file, sourcefile.txt. I want to take this line and put it in a POST web request using .NET functionality.
After looking into it, I chose to use the httpwebrequest class. Below is what I have so far--I got this from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL");
bob.Method = "POST";
bob.ContentType = "application/json";
byte[] bytearray = File.ReadAllBytes(#"sourcefile.txt");
Stream datastream = bob.GetRequestStream();
datastream.Write(bytearray, 0, bytearray.Length);
datastream.Close();
Am I going about this correctly? I am relatively new to web technologies and still learning how http calls work.
Here is a method I use for creating POST requests:
private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint)
{
HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
request.Proxy = null;
request.Method = "POST";
//Specify the xml/Json content types that are acceptable.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", apikey);
request.Headers.Add("Secretkey", secretkey);
return request;
}
Within my main method I call it like this:
HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint);
and I then pass my data to the method like this:
string requestBody = SerializeToString(requestObj);
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Business error
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString()));
return "error";
}
else if (response.StatusCode == HttpStatusCode.OK)//Success
{
using (Stream respStream = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse));
reportReq = serializer.Deserialize(respStream) as SubmitReportResponse;
}
}
...
In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.