简体   繁体   中英

How do I send a POST Request to Google Translate Api using a C# WebClient?

I googled now for almost an hour and can't find anything that would help me out. I'm a beginner programer and took the course over from TeamTreeHouse with Serialization in C#. Here I also learned how to use the WebClient.

Now I thought a good practice Project would be to make a Translate app that sends to google the user input in a POST Request and Google returns the answer as Json which I deserialize.

Problem is I read through the documentation of the api but I'm so confused of what I should send exactly to google and really how to do this?

I know the method webclient.Headers.Add(arguments here) , but I really don't know what else it needs.

You can find an example over here:

https://cloud.google.com/translate/docs/translating-text

https://translation.googleapis.com/language/translate/v2 Three query parameters are required with each translation request:

Target language : Use the target parameter to specify the language you want to translate into. Source text string : Use the q parameter to specify each text string to translate. API key : Use the key parameter to identify your application. If you are using OAuth 2.0 service account credentials (recommended), do not supply this parameter.

So problem is there is no placeholder in that example URL where I could put my api key + soure text string an Target language.

So what exactly should I send to google so it knows what I want and returns me the JSON file?

Maybe anyone could help me out. And I know there is an official Library for exactly this but I want to practice serialization and using web scraping with the WebClient class so I want to do it like this.

You specifically asked about a POST.

  1. You can use this url:

    https://translation.googleapis.com/language/translate/v2?key=MY_KEY

Of course, replace MY_KEY with your key.

  1. Add a header for the content type:

    application/json; charset=utf-8

  2. Format your text and target language as JSON and write it to your request stream:

    {"q":"Team work is a major progress maker at this location, it appears that everyone is willing to help when they can.","target":"fr"}

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