How can i encode a string to http web request ?

Răspuns How can i encode a string to http web request ?

  • 1 mai 2012 15:36
     
      Are cod

    I need to send a string to a website and get back a result.

    But for example if i send "hello world" it should be "hello%world" instead of space there should be a %

    There should be a way i think to make it automatic so it will know where how and when to put this % when the string have spaces in this location.

    For example i have this string wich is a site url:

    https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de

    There is a %20 between the hello and the world. How can i do it ?

    Thanks.


    danieli

Toate mesajele

  • 1 mai 2012 15:54
     
     Răspuns propus Are cod
    string result = System.Web.HttpUtility.UrlEncode("hello world");

    By the way, the url encoding of a space is "%20" not "%".
  • 1 mai 2012 15:58
     
      Are cod

    I tried to use the example on the web but it dosent work good. Could you fix it show me the right code please ?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Web;
    using System.IO;
    
    namespace GoogleTranslateing
    {
        public partial class Form1 : Form
        {
            string apiKey = "My key";
            string sourceLanguage = "en";
            string targetLanguage = "de";
            string googleUrl;
            string textToTranslate = "hello world";
    
            public Form1()
            {
                InitializeComponent();
    
                googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;
    
                webRequest();
    
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            private void webRequest()
            {
                // Create a request using a URL that can receive a post. 
                WebRequest request = WebRequest.Create(googleUrl);
                // Set the Method property of the request to POST.
                request.Method = "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";
                // 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();
            }
        }
    }
    


    danieli

  • 1 mai 2012 16:31
     
     

    I've showed you exactly the method that you need to use.  You should call it on each of the parameters before concatting them into the URL.

    If you're too lazy to do it then I guess solving this problem isn't very important to you.  I've given you everything that you need to solve the problem yourself.

  • 1 mai 2012 17:21
     
     Răspuns propus

    Also consider Uri.EscapeDataString, for example:

    googleUrl = string.Format"https://www.googleapis.com/language/translate/v2?key={0}&q={1}&source={2}&target={3}",
                                Uri.EscapeDataStringapiKey ),
                                Uri.EscapeDataStringtextToTranslate ),
                                Uri.EscapeDataStringsourceLanguage ),
                                Uri.EscapeDataStringtargetLanguage ) );

  • 1 mai 2012 18:13
     
     

    "Also consider Uri.EscapeDataString, for example:"

    It'll do the same thing.

  • 2 mai 2012 07:49
    Moderator
     
     Răspuns Are cod

    Hi Chocolade,

    Please note this: You can encode a URL using with the UrlEncode() method or the UrlPathEncode() method. However, the methods return different results. The UrlEncode()method converts each space character to a plus character (+). The UrlPathEncode() method converts each space character into the string "%20", which represents a space in hexadecimal notation. Use the UrlPathEncode() method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

    Thus, I recommend you use UrlPathEncode() method. You can refer to this page: http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx

    You can try these:

    String apiKey = System.Web.HttpUtility.UrlPathEncode("My key");
    String sourceLanguage = "en";
    String targetLanguage = "de";
    String textToTranslate = System.Web.HttpUtility.UrlPathEncode("hello world");
    String url = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;

    Have a nice day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marcat ca răspuns de chocolade 2 mai 2012 09:15
    •