

Unityでhololens用のアプリケーションを作成しています。  
AzureのTranslator Text API を使用したいのですがうまく動きません。  
エラーとコードを載せますのでわかりましたら教えてください。  
参考にしたサイトは <https://blogs.msdn.microsoft.com/dataplatjp/2017/12/07/translator-
text-api-sample/> です。

追記:2018年7月19日17時54分  
回答をいただき証明書に関して無視して動作するように追加しました。  
なのですが、UWPとしてアプリをビルドすることができません。  
以下、エラーは4つです。  
エラー1

[code]

    Assets\Script\TrustAllCertificatePolicy.cs(3,42): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you missing a using directive or an assembly reference?)
    
[/code]

エラー2

[code]

     Assets\Script\TrustAllCertificatePolicy.cs(6,50): error CS0234: The type or namespace name 'ServicePoint' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
    
[/code]

エラー3

[code]

    Assets\Script\TrustAllCertificatePolicy.cs(7,38): error CS0234: The type or namespace name 'X509Certificates' does not exist in the namespace 'System.Security.Cryptography' (are you missing an assembly reference?)
    
[/code]

エラー4

[code]

    Error building Player because scripts had compiler errors
    
[/code]

エラー5

[code]

    Build completed with a result of 'Failed'
    UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
    
[/code]

エラー6

[code]

    UnityEditor.BuildPlayerWindow+BuildMethodException: 4 errors
      at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (BuildPlayerOptions options) [0x00207] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:172 
      at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) [0x00050] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:83 
    UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
    
[/code]

**_以下の部分は解決済みです_**  
OnInputClickedはHololensのinputイベントです。  
Debug.logの結果はin!!まで出ていいます。  
エラーが出るのは「response = httpWebRequest.GetResponse();」の部分です。(53行目)

[code]

    using HoloToolkit.Unity.InputModule;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using UnityEngine;
    
    public class Test : MonoBehaviour, IInputClickHandler
    {
        string uri, ocpApimSubscriptionKey;
        // Use this for initialization
        void Start()
        {
            uri = GetUri("hello");
            ocpApimSubscriptionKey = "hogehoge";//key
        }
    
        // Update is called once per frame
        void Update()
        {
    
        }
        private string GetUri(string inputText)
        {
            //翻訳前の言語
            string fromLanguage = "en";
            // 翻訳語の言語
            string toLanguage = "ja";
            //利用するモデル  ：空白 (=統計的機械翻訳) or generalnn(=ニューラルネットワーク)を指定
            string ModelType = "generalnn";
            //Translator Text API の Subscription Key（Azure Portal(https://portal.azure.com)から取得）
    
            //URIの定義（Getでパラメータを送信する為、URLに必要なパラメーターを付加）
            string uri = "https://api.microsofttranslator.com/v2/http.svc/Translate?" +
            "&text=" + Uri.EscapeDataString(inputText) +
            "&from=" + fromLanguage +
            "&to=" + toLanguage +
            "&category=" + ModelType;
            return uri;
        }
        private IEnumerator UseAPI()
        {
            //httpWebRequestの作成
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    
            //Authorizationのためにhttpヘッダーにサブスクリプションキーを埋め込む
            httpWebRequest.Headers.Add("Ocp-Apim-Subscription-Key:" + ocpApimSubscriptionKey);
    
            WebResponse response = null;
    
            //Translator Text APIへのリクエストを実行して結果を取得
            response = httpWebRequest.GetResponse(); // **ここでエラーがはかれる**
            Debug.Log("wait");
            yield return response;
            Debug.Log("finish");
            using (Stream stream = response.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs =
                new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                string translationText = (string)dcs.ReadObject(stream);
                Debug.Log(translationText);
            }
        }
    
        public void OnInputClicked(InputClickedEventData eventData)
        {
            Debug.Log("in!!");
            StartCoroutine(UseAPI());
        }
    }
    
[/code]

エラー内容:

[code]

    TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates)
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 ()
    Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process ()
    (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()
    Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg)
    Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
    Rethrow as IOException: The authentication or decryption has failed.
    Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
    Rethrow as WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
    System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
    System.Net.HttpWebRequest.GetResponse ()
    Test+<UseAPI>c__Iterator0.MoveNext () (at Assets/Script/Test.cs:53)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
    UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
    Test:OnInputClicked(InputClickedEventData) (at Assets/Script/Test.cs:68)
    HoloToolkit.Unity.InputModule.InputManager:<OnInputClickedEventHandler>m__4(IInputClickHandler, BaseEventData) (at Assets/HoloToolkit/Input/Scripts/Utilities/Managers/InputManager.cs:402)
    UnityEngine.EventSystems.ExecuteEvents:ExecuteHierarchy(GameObject, BaseEventData, EventFunction`1)
    HoloToolkit.Unity.InputModule.InputManager:HandleEvent(BaseEventData, EventFunction`1) (at Assets/HoloToolkit/Input/Scripts/Utilities/Managers/InputManager.cs:296)
    HoloToolkit.Unity.InputModule.InputManager:RaiseInputClicked(IInputSource, UInt32, InteractionSourcePressInfo, Int32, Object[]) (at Assets/HoloToolkit/Input/Scripts/Utilities/Managers/InputManager.cs:411)
    HoloToolkit.Unity.InputModule.InteractionInputSource:GestureRecognizer_Tapped(TappedEventArgs) (at Assets/HoloToolkit/Input/Scripts/InputSources/InteractionInputSource.cs:971)
    UnityEngine.XR.WSA.Input.GestureRecognizer:InvokeTapped(InteractionSource, InteractionSourcePose, Pose, Int32)
    
[/code]


CC BY-SA 4.0
2018-07-19T05:46:07.850
46718
2020-06-12T08:01:15.167
2018-07-19T09:00:50.323
29372
29372
question
c# unity3d api azure 非同期
UnityでTranslator Text API を使用する方法について


[TlsExceptionを解消](http://masa795.hatenablog.jp/entry/2013/07/08/214336)
という記事に質問と同様のエラーへの対処が書かれています。参考になるのではないでしょうか。


CC BY-SA 4.0
2018-07-19T06:01:46.837
46720
2018-07-19T06:01:46.837
217
46718
answer