[Windows 8 App]HttpWebRequest翻譯應用(下)
這裡是關於 AdmaAuthentication 的程式碼如下:
public class AdmaAuthentication
{
public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
private string clientId;
private string clientSecret;
private string request;
public AdmaAuthentication(string clientId, string clientSecret)
{
this.clientId = clientId;
this.clientSecret = clientSecret;
this.request = string.Format("grant_type = client_creadentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", System.Net.WebUtility.UrlEncode(clientId), System.Net.WebUtility.UrlEncode(clientSecret));
}
public Task<AdmAccessToken> GetAccessToken()
{
return HttpPost(DatamarketAccessUri, this.request);
}
private async Task<AdmAccessToken> HttpPost(string DatamarketAccessUri, string requestDetails)
{
WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(requestDetails);
using (Stream outputStream = await webRequest.GetRequestStreamAsync())
{
outputStream.Write(bytes, 0, bytes.Length);
}
using (WebResponse webResponse = await webRequest.GetResponseAsync())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
return token;
}
}
}
由於AdmaAuthentication 類別是來自微軟官方,這裡我們就不對其做詳細的解釋
接下來看一下,翻譯按鈕的Click事件是如何實現的
此按鈕透過HTTP請求將要翻譯的英文送給翻譯伺服器,並接收服務器的回應數據
關於 BtnTranslate_Click 的程式碼如下:
private async void BtnTranslate_Click(object sender, RoutedEventArgs e)
{
string text = TxtEnglish.Text;
string from = "en";
string to = "zh-TW";
string uri = "https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=" + System.Net.WebUtility.UrlEncode(text) + "&from" + from + "&to" + to;
string authToken = "Bearer" + " " + token.access_token;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers["Authorization"] = authToken;
WebResponse response = null;
try
{
response = await httpWebRequest.GetResponseAsync();
using (Stream stream = response.GetResponseStream())
{
System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
string translation = (string)dcs.ReadObject(stream);
TxtChinese.Text = translation;
}
}
catch (Exception ex)
{
TxtMessage.Text = ex.Message;
}
}
上面的程式碼中,首先取得輸入的英文語句,並定義請求字符串 uri
以 uri 為參數呼叫非同步方法 WebRequest.Create 建立HTTP請求 httpWebRequest
由於翻譯需要使用到權限的驗證
所以這裡使用了在前面獲得的客戶端 token 來請求 Headers 中的 Authorization 鍵賦值
最後,將翻譯出來的字符串輸出到文字方塊中
專案執行的畫面如下:
這是初始畫面
這是翻譯 apple 蘋果 的結果
這是翻譯歡迎來到微軟