Sending large amounts of POST data - c#

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();
}

Related

How can a pass a body with my POST and DELETE request using Http Web Request

I have a Generic method SendRequest that sends request to get the OAuth token at the run time and then also uses to Send my request to the server. I have few POST and DELETE call that takes a body of list or a string. But I do not know how to set it. I know how to send the Json and by serialize it but I am having trouble how to add a body when its just a string or a list type.
public HttpWebResponse SendRequest(string postData = "", Authentication.TokenType tokenType = Authentication.TokenType.Valid)
{
var messageBody = postData;
var strResponseValue = string.Empty;
var request = (HttpWebRequest)WebRequest.Create(EndPoint);
if (EndPoint == StringBuilderUtil.GenerateRequestURL("token"))
{
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "identity-authority." +
ConfigurationManager.AppSettings["TestEnvironment"];
Token = ConfigurationManager.AppSettings["GenericSpecialCode"];
}
else
{
request.ContentType = "application/json";
Token = Authentication.ChooseToken(tokenType);
}
if (HttpMethod == HttpVerb.POST)
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
// Add some headers that are common to all calls.
request.KeepAlive = true;
request.Headers.Add("Authorization", AuthType.ToString() + " " + Token);
request.Method = HttpMethod.ToString();
request.Headers.Add("Cache-Control", "no-cache");
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ec6hh.png
how to add a body when its just a string or a list type.
If you are sending a string you don't have to do much apart from encoding and putting it into the stream.
list type goes the same way as object. You have to serialize it first.
There is logic already for the last two things.
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
I assume serialization happens before calling SendRequest method and if you are using Newtonsoft.Json it can be done with JsonConvert.SerializeObject

Postmates API not working

I am using postmates Delivery Quote API for the last one year, And it is working good by the time when I checked.
But now it seems to be not working
It is throwing an exception with an HTML text with some enable cookies and captcha
I can't understand if i am missing some updates from postmates
Here is my coding
HttpWebRequest req = WebRequest.Create(new Uri("https://api.postmates.com/v1/customers/" + PostmatesCustomerId + "/delivery_quotes")) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Authorization", "Basic " + Base64string);
StringBuilder paramz = new StringBuilder();
paramz.Append("pickup_address=" + PickUpAddress + "&dropoff_address=" + DeliveryAddress);
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
req.ContentLength = formData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
string responseString = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
responseString = reader.ReadToEnd();
}
If you're outside of the US, try using a VPN as a workaround to test.

How to use WebRequest in c#

I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}

post data through httpwebrequest and get it in php

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";
}

Sending File in Chunks to HttpHandler

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

Categories