Google Translator API "Too Large URL" - c#

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.

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

Spaces being removed when posting data from ASPX to ASP page, but spaces preserved when posting to ASPX page

Spaces being removed when posting data from ASPX to ASP page, but spaces preserved when posting data to ASPX page. Below is the sample code
calling program code (aspx code behind)
WebRequest request = WebRequest.Create("http://localhost/asppost/asppost.asp");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "LastName=Ahamed&Addr1=100 Main Street";
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.
Debug.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.
Debug.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
asppost.asp
<%
Dim Lname, AddressLine1
Lname = Request.Form("LastName")
AddressLine1 = Request.Form("AddressLine1")
Response.Write("Last Name: " & Lname)
Response.Write(" Address Line1: " & AddressLine1)
%>
output
OK
Last Name: Ahamed Address Line1: 100MainStreet
Problem will be solved if I use HttpUtility.UrlEncode as below, but my question is why and how spaces are preserved when posting the same data (without UrlEncode) to ASPX page?
string postData = "LastName=" + HttpUtility.UrlEncode("Ahamed") + "&AddressLine1=" + HttpUtility.UrlEncode("100 Main Street");
Please share your ideas.
The data in your postData string needs to be URL Encoded.
This postData = "LastName=Ahamed&Addr1=100 Main Street";
needs to be: postData = "LastName=Ahamed&Addr1=100+Main+Street";
In code this will be something like:
string postData = "LastName=" + HttpUtility.UrlEncode(lastName);
postData += "&Addr1=" + HttpUtility.UrlEncode(addr1);

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

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

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