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
Related
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.
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").
So i'm making a program where you input some information. One part of the information requires alot of text, we are talking 100+ characters. What I found is when the data is to large it won't send the data at all. Here is the code I am using:
public void HttpPost(string URI, string Parameters)
{
// this is what we are sending
string post_data = Parameters;
// this is where we will send it
string uri = URI;
// create a request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
I am then calling that method like so:
HttpPost(url, "data=" + accum + "&pass=HRS");
'accum' is the large amount of data that I am sending. This method works if I send a small amount of data. But then when it's large it won't send. Is there any way to send a post request to a .php page on my website that can exceed 100+ characters?
Thanks.
You're only calling GetRequestStream. That won't make the request - by default it will be buffered in memory, IIRC.
You need to call WebRequest.GetResponse() to actually make the request to the web server.
So change the end of your code to:
// Using statement to auto-close, even if there's an exception
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// Now we're ready to send the data, and ask for a response
using (WebResponse response = request.GetResponse())
{
// Do you really not want to do anything with the response?
}
I'm using this way to post JSON data inside the request , I guess it's a little bit different but it may work ,
httpWebRequest = (HttpWebRequest)WebRequest.Create(RequestURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
String username = "UserName";
String password = "passw0rd";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{" +
"\"user\":[ \"" + user + "\"] " +
"}";
sw.Write(json);
sw.Flush();
sw.Close();
}
using (HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
}
httpResponse.Close();
}
Hello I try to write a HTTP Request in C# (Post), but I need help with an error
Expl: I want to send the Content of a DLC File to the Server and recive the decrypted content.
C# Code
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + dlc_content);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
and here I got the html request
<form action="/decrypt/paste" method="post">
<fieldset>
<p class="formrow">
<label for="content">DLC content</label>
<input id="content" name="content" type="text" value="" />
</p>
<p class="buttonrow"><button type="submit">Submit ยป</button></p>
</fieldset>
</form>
Error Message:
{
"form_errors": {
"__all__": [
"Sorry, an error occurred while processing the container."
]
}
}
Would be very helpfull if someone could help me solving the problem!
You haven't set a content-length, which might cause issues. You could also try writing bytes directly to the stream instead of converting it to ASCII first.. (do it the opposite way to how you're doing it at the moment), eg:
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content));
request.ContentLength = _byteVersion.Length
Stream stream = request.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
I've personally found posting like this to be a bit "fidgity" in the past. You could also try setting the ProtocolVersion on the request.
I would simplify your code, like this:
public static void decryptContainer(string dlc_content)
{
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "content", dlc_content }
};
client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
string url = "http://dcrypt.it/decrypt/paste";
byte[] result = client.UploadValues(url, values);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
It also ensures that the request parameters are properly encoded.
public string void decryptContainer(string dlc_content) //why not return a string, let caller decide what to do with it.
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//sure this is needed? Maybe just match the one content-type you expect.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + Uri.EscapeDataString(dlc_content));//escape the value of dlc_content so that the entity sent is valid application/x-www-form-urlencoded
}
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())//this should be disposed when finished with.
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
There could still be a problem with what is actually being sent.
One issue I see right away is that you need to URL encode value of the content parameter. Use HttpUtility.UrlEncode() for that.
Other than that there might be other issues there, but it is hard to say not knowing what service does. The error is too generic and could mean anything
request.ContentLength should be set as well.
Also, is there a reason you are ASCII encoding vs UTF8?
Get the stream associated with the response first then pass that into the Streamreader as below:
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
Console.WriteLine(reader.ReadToEnd());
}
As I can't comment on the solution of Jon Hanna. This solved it for me:
Uri.EscapeDataString
// this is what we are sending
string post_data = "content=" + Uri.EscapeDataString(dlc_content);
// this is where we will send it
string uri = "http://dcrypt.it/decrypt/paste";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);
I have this php code in server :
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
and i am sending post data by httpwebrequest in c# :
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
static html codes of php page are shown.
but nothing of posted value are shown in messagebox .that means no data are posted.
what is wrong?
You need to get the bytes of the data.
Try this code, from this guy's blog post.
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}