简体   繁体   中英

How do I POST multiple values with the same key (to Google Translate) using the simple C# WebClient

I wish to send multiple values to the Google Translate API using the simple syntax provided by the C# WebClient . To send multiple values to the API, each value has to have the same query-string key, for example: q=value1&q=value2 .

I cannot use the default GET mechanism and simply put these values on the query-string because some of my values are too large. I therefore have to POST these values making sure I set the X-HTTP-Method-Override header.

The problem is, to POST my values I need to use the WebClient.UploadValues() method which expects the values to be presented as a NameValueCollection . Multiple values with the same key are supported by the NameValueCollection but not in a way that the Google Translate API will recognise as separate values (it creates a simple comma delimited set of values held under a single key unique key).

How do I POST multiple values, each with the same key, using the WebClient class?

For further reading see:

To do this you can use the WebClient.UploadString() method, although there are a couple of gotchas to note. First some code:

using (var webClient = new WebClient())
{
    webClient.Encoding = Encoding.UTF8;
    webClient.Headers.Add("X-HTTP-Method-Override", "GET");
    webClient.Headers.Add("content-type", "application/x-www-form-urlencoded");
    var data = string.Format("key={0}&source={1}&target={2}&q={3}&q={4}", myApiKey, "en", "fr", urlEncodedValue1, urlEncodedvalue2);
    try
    {
        var json = webClient.UploadString(GoogleTranslateApiUrl, "POST", data);
        var result = JsonConvert.DeserializeObject<dynamic>(json);
        translatedValue1 = result.data.translations[0].translatedText;
        translatedValue2 = result.data.translations[1].translatedText;
    }
    catch (Exception ex)
    {
        loggingService.Error(ex.Message);
    }
}

You can see that I am formatting the data to be sent to the Google Translate API as a application/x-www-form-urlencoded string. This allows multiple values with the same key to be formatted together.

To post this correctly You must remember to set the WebClient.Encoding property, in my case to UTF8 , as the WebClient converts the string to be uploaded into an array of bytes before posting them.

You must also remember to set the content-type header to application/x-www-form-urlencoded thus ensuring the payload is correctly packaged.

Finally you have to remember to urlencode the values to to be translated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM