posting data to PHP from C# - 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);

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 { }
}
}

C# HttpWebRequest.Write does not send content

Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//
request.Method = "POST";
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
Stream requestBodyStream = request.GetRequestStream();
requestBodyStream.Write(requestBody, 0, requestBody.Length);
requestBodyStream.Flush();
requestBodyStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.
I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.
My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.
Why is this method not producing any body?
Add 'ContentType' and 'ContentLength' headers to the request instance:
request.ContentType = "application/json"; // Or whatever you want
request.ContentLength = requestBody.Length;

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.

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

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

How to get a response page after submit on csharp?

There is a page in remote web-site, where one can enter input values in forms, click a button and get a result in output form.
I want to send a request to the page with filling necessary input forms, submit it and get a result page with output form filled.
All threads with similar topics give the code samples like this:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.site.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 = string.Format("inputParam=value");
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();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
response.Close();
It returns a page with filled input forms, but output field is still blank, like it doesn't do a commit button click.
How can I do a commit from my C# code and receive an html document with output data?
Change the webresponse section to the following;
WebResponse response = request.GetResponse ();
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();

Categories