I've always done my web services in PHP. Now I'm trying some ASP.NET on a project and I found myself on a tricky situation. I have the following C# code, behaving as a "client"
public void sendRequest(string URL, string JSON)
{
ASCIIEncoding Encode = new ASCIIEncoding();
byte[] data = Encode.GetBytes(JSON);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
returnRequestTxtBx.Text = responseText;
}
Well, now I want to handle on the ASPX.CS side...
my question is... how do I access the data I sent as a POST?
Is there a way in the "Page_Load" method that I can handle the JSON I sent?
To read post method data on your server side read HttpContext.Request.Form method:
protected void Page_Load(object sender, EventArgs e)
{
string value=Request.Form["keyName"];
}
Or if you want to access row body data simply read: Request.InputStream.
And if you want handle Json format consider Newtonsoft.Json packege.
Related
I am new with web service and API's and trying to get a response from a URL with a post method and passing a parameter to it. I am developing a C# winform application that sending request to this api and must return the output in JSON format. Below is my code so war i only getting an OK response instead of the actual JSON data.
private void button1_Click(object sender, EventArgs e)
{
string postData = "station=sub";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Uri target = new Uri("http://apijsondata/tz_api/");
WebRequest myReq = WebRequest.Create(target);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = byteArray.Length;
using (var dataStream = myReq.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (var response = (HttpWebResponse)myReq.GetResponse())
{
//Do what you need to do with the response.
MessageBox.Show(response.ToString());
}
}
You should use a StreamReader together with HttpWebResponse.GetResponseStream()
For example,
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
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.
Please refer to the below code. How can I test/debug, whether the below code worked correctly or not. It runs and there are no compilation/runtime errors.
The end result of the below code is to set one of the controls in the page, to hold the POST data from below code. However I haven't come that far yet.
protected override void OnInit(EventArgs e)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "http://s.com/is/image/scom/2Peel";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://m.com/Confirm.aspx?ID=175");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
Update 1: I tried to find out the response using below code, but the page doesn't load at all.
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
Use the GetResponse method of your HttpWebRequest object (which you named "myRequest").
I have a problem with posting of binary data to server via HttpWebRequest. Here is my client code:
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.UserAgent = RequestUserAgent;
request.ContentType = "application/x-www-form-urlencoded";
var responseStr = "";
var dataStr = Convert.ToBase64String(data);
var postData = Encoding.UTF8.GetBytes(
string.Format("uploadid={0}&chunknum={1}&data={2}", uploadId, chunkNum, dataStr));
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
dataStream.Close();
}
And then I want to work with request via MVC controller, here is it's signature:
public ActionResult UploadChunk(Guid? uploadID, int? chunkNum, byte[] data)
But I have error here, saying that data is not Base64 coded array, what am I doing wrong?
You need to escape the + characters in your Base64 by calling Uri.EscapeDataString.
I'm trying to send a file in chunks to an HttpHandler but when I receive the request in the HttpContext, the inputStream is empty.
So a: while sending I'm not sure if my HttpWebRequest is valid
and b: while receiving I'm not sure how to retrieve the stream in the HttpContext
Any help greatly appreciated!
This how I make my request from client code:
private void Post(byte[] bytes)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2977/Upload");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.SendChunked = true;
req.Timeout = 400000;
req.ContentLength = bytes.Length;
req.KeepAlive = true;
using (Stream s = req.GetRequestStream())
{
s.Write(bytes, 0, bytes.Length);
s.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
}
this is how I handle the request in the HttpHandler:
public void ProcessRequest(HttpContext context)
{
Stream chunk = context.Request.InputStream; //it's empty!
FileStream output = new FileStream("C:\\Temp\\myTempFile.tmp", FileMode.Append);
//simple method to append each chunk to the temp file
CopyStream(chunk, output);
}
I suspect it might be confusing that you are uploading it as form-encoded. but that isn't what you are sending (unless you're glossing over something). Is that MIME type really correct?
How big is the data? Do you need chunked upload? Some servers might not like this in a single request; I'd be tempted to use multiple simple requests via WebClient.UploadData.
i was trying the same idea and was successfull in sending file through Post httpwebrequest. Please see the following code sample
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName +
"&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}
I have blogged about it, you see the whole HttpHandler/HttpWebRequest post here
http://aspilham.blogspot.com/2011/03/file-uploading-in-chunks-using.html
I hope this will help