How to retrieve the posted data (in byte[] format)? - c#

I have a C# .net web application. I am trying to post a binary data from one application to another using this code
string url = "path to send the data";
string result=null;
string postData = "This is a test that posts this string to a Web server.";
byte[] fileData = Encoding.UTF8.GetBytes (postData);
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create (url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data";
// Set the ContentLength property of the WebRequest.
request.ContentLength = fileData.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (fileData, 0, fileData.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
result = ((HttpWebResponse)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.
result = result + responseFromServer;
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close();
By the above code, I am sending byte[] to a second application. How can I retrieve the posted data (in byte[] format) in the second application?

Note: I assume that you are asking about how to retrieve the posted data in second application and also you have access to the code of second application.
Then if it is a webform application then simply on page_load event you can get file name and file itself as:
string strFileName = Request.Files[0].FileName;
HttpPostedFileBase filesToSave = Request.Files[0];
If this is not the requirement, then edit your question and add more details.

EDIT: Updated answer to include both Request and Server side. Server side converts Base64 string to a byte[].
If you're going to post binary data that was read into a byte[], you'll have to convert it to a Base64 string on request side to post it.
Client/Request Side:
byte[] byteData = ReadSomeData();
string postData = Convert.ToBase64String(byteData);
Then on the server side, use the HttpContext to get the InputStream from the Request property. You can then use a StreamReader and its ReadToEnd() method to read in the data. You then convert the posted Base64 string to a byte[].
Something like this:
string postData = string.Empty;
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
postData = inputStreamReader.ReadToEnd();
}
byte[] data = Convert.FromBase64String(postData);

Related

Why am I not recieving a response from the webrequest?

So i'm trying to learn how WebRequest & WebResponse works.
So far it seems a bit like when you create a TcpClient and listener and make them connect and then send a buffer inbetween them.
However this seems to be a bit different.
So what im doing here is that im making a request to a website, in this case Spotify (Thought I would try to login to spotify as my first project).
Using the POST method to post data to the website.
converting my string to a byteArray
changing the contenttype (Not really sure if im doing it right here, not 100% sure what the values can be)
and the length of the content is the length of the byteArray
I create a stream of data in which I will get the stream from the request.
and then I proceed to write the byteArray starting from the offset of 0 and then the length of the thing that im going to write.
then I close the dataStream.
Now I create a WebResponse (which will get the response to tell me if everything is okay or not (im assuming))
Then I print out the the statusdescription (It doesnt print out anything here not sure why)
Then I create a stream that contains the content from the server
and then I create a streamreader which will read the content..
The rest is pretty straight forward.
Issue
So the issue is that its not printing out anything to the console and I am not sure why. How do I make it print out?
ERROR
So I caught the exception and this is what img etting
"The remote server returned an error: <405> Method not allowed."
CODE
class Program
{
static void Main(string[] args)
{
Console.Title = "Login Test";
Console.ForegroundColor = ConsoleColor.Green;
tester();
Console.ReadLine();
}
private static void tester()
{
try
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://accounts.spotify.com/en-SK/login");
// 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.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)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);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch { }
}
}

Google Translator API "Too Large URL"

I have recently started working on Translator API and I am getting the ERROR Too Large URL when my input text exceeds 1300 characters.
I am using the below code
string apiKey = "My Key";
string sourceLanguage = "en";
string targetLanguage = "de";
string googleUrl;
string textToTranslate =
while (textToTranslate.Length < 1300)
{
textToTranslate = textToTranslate + " hello world ";
}
googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;
WebRequest request = WebRequest.Create(googleUrl);
// Set the Method property of the request to POST^H^H^H^HGET.
request.Method = "GET"; // <-- ** You're putting textToTranslate into the query string so there's no need to use POST. **
//// Create POST data and convert it to a byte array.
//string postData = textToTranslate;
//byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// ** Commenting out the bit that writes the post data to the request stream **
//// Set the ContentLength property of the WebRequest.
//request.ContentLength = byteArray.Length;
//// Get the request stream.
//Stream dataStream = request.GetRequestStream();
//// Write the data to the request stream.
//dataStream.Write(byteArray, 0, byteArray.Length);
//// Close the Stream object.
//dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream 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);
Console.WriteLine(i);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Can You please suggest me that what kind of changes i can do in my code, so that the input text limit can be increased unto 40k - 50k per request.
At some point someone has changed your code from making a POST request to making a GET.
GET puts all the data into the URL instead of putting it in the request body. URLs have a length limit. Go back to using POST and this problem will go away. Refer to the documentation for your HTTP client library to find out how to do this.

posting data to PHP from C#

HI I have been trying to post data to PHP webservice(3rd party) from my C# code.
The PHP webservice says it expects a parameter c (missing parameter c is the error I get).
I am using JSON to send the data, but i do not understand how do give the parameter. Would be great if some one could throw light on this.The following is my code:
DropYa d = new DropYa();
List<DropYaUser> d1 = new List<DropYaUser>();
DropYaUser ds = new DropYaUser();
ds.action = "create";
ds.groupid = 10;
ds.name = "Test";
ds.manager_key = "test";
d1.Add(ds);
WebRequest request = WebRequest.Create(" http://dev.dropya.net/api/Group.php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
JavaScriptSerializer ser = new JavaScriptSerializer();//typeof(DropYaUser));
string postData = ser.Serialize(ds);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Console.Write("Wrote");
Console.Read();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Console.Read();
dataStream = response.GetResponseStream();
Console.Read();
// 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);
// Clean up the streams.
reader.Close();
dataStream.Close();
Console.Read();
response.Close();
Any post request is going to be read as a data stream. The field names and values for a posted form will appear in the stream in a form like "c=ABC&d=123", where 'c' and 'd' are form fields. Of course you can post without any form field names but in this case it is expecting 'c'. What you'll want to do is prepend "c=" to the data you're posting. Perhaps modify your GetBytes line like so:
byte[] byteArray = Encoding.UTF8.GetBytes("c=" + postData);

How to login to the android market using C#?

I would like to login to the webpage Android Market using C#. I spent the whole day reading about HTTP requests and POST data, but nothing seems to work. What I can do is read the webpage that holds the google login form. But reading the page AFTER the login seems impossible...
Can anyone give me a hint on how to do this?
BTW: The code I've tried is shown below:
string mail = "XXXXXXXXXX#gmail.com";
string pw = "XXXXXXXXXX";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create (#"https://market.android.com/publish");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = String.Format ("Email={0}&Passwd={1}&signIn=Sign+in", mail, pw);
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.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)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);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
What I usually do: get live http headers for firefox and you can record the request your browser sends. Then simply repeat that in code.
for example, the android marketplace does it pretty different from your code.
it actually posts to: https://accounts.google.com/ServiceLoginAuth
And posts the data continue=https%3A%2F%2Fmarket.android.com%2Fpublish%2FHome&followup=https%3A%2F%2Fmarket.android.com%2Fpublish%2FHome&service=androiddeveloper&nui=1&dsh=&GALX=&pstMsg=1&dnConn=&timeStmp=&secTok=&Email=Passwd=&signIn=
You need to create a CookieContainer instance and assign it to the CookieContainer property in each request.
This will store the login cookie so that the site knows that you're still logged in.

finding c# ways to send http requests

I am trying to develop a Microsoft excel plugin to send excel sheet data to a web application. It will require the plugin to prompt username and password and then send login http request to the web application to get a session . Then it will upload data to the web application . What .net things should I use ?
Post Method Sample for send username and password. for uploading file just search "File Upload C#" in google.com or bing.com or try C#'s WebClient.UploadFile, Code Project
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://example.com");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "username=user&passsword=pass";
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.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)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);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close();
For HTTP communication in .NET, try System.Net.WebClient or System.Net.HttpWebRequest.

Categories