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.
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.
I am trying test out a REST service implemented as follows:
public bool loadData(string file, string page, string mapping, [FromBody]string value)
{
// Implementation
}
The code I am using to invoke this service:
uri = "http://localhost:9576/API/DataLoaderService?file=F&page=P&mapping=M";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = Method.ToUpper();
byte[] buffer = Encoding.ASCII.GetBytes("TEST_STRING");
req.ContentLength = buffer.Length;
req.ContentType = "application/x-www-form-urlencoded";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
However the "TEST_STRING" does not get bound to the [FromBody]string value.
As you can see in this my previous question (little different from yours) when you use [FromBody] you should use = and then the value of the parameter.
So in your case try
byte[] buffer = Encoding.ASCII.GetBytes("=TEST_STRING");
instead of
byte[] buffer = Encoding.ASCII.GetBytes("TEST_STRING");
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);
}
I have the following problem.
I have the method that sends json via POST:
public string request (string handler, string data)
{
WebRequest request = WebRequest.Create(baseUri + "/?h=" + handler);
request.Method = "POST";
request.ContentType = "text/json";
string json = "json=" + data;
byte[] bytes = Encoding.ASCII.GetBytes(json);
request.ContentLength = bytes.Length;
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
WebResponse res = request.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
lastResponse = sr.ReadToEnd();
return lastResponse;
}
When using the method on the server does not come data in POST. As if this code is not executed.
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
On the server i'm using following php script for debug:
<?php print_r($_POST); ?>
Also tried to write to the stream as follows:
StreamWriter strw = new StreamWriter(request.GetRequestStream());
strw.Write(json);
strw.Close();
The result - a zero response. In response comes an empty array.
The Problem is, that PHP does not "recognize" the text/json-content type. And thus does not parse the POST-request-data. You have to use the application/x-www-form-urlencoded content-type and secondly you have to encode the POST-data properly:
// ...
request.ContentType = "application/x-www-form-urlencoded";
string json = "json=" + HttpUtility.UrlEncode(data);
// ...
If you intend to supply the JSON-data directly you can leave the content-type to text/json and pass the data directly as json (without the "json=" part):
string json = data;
But in that case you have to change your script on the PHP-side to directly read the post data:
// on your PHP side:
$post_body = file_get_contents('php://input');
$json = json_decode($post_body);
Have you thought about using WebClient.UploadValues. Using the NameValueCollection with "json" as the name and JSON data string as the value?
This seems like the easiest way to go. Don't forget you can always add headers and credentials to the WebClient.
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