简体   繁体   English

连接到Text Analytics API时,为什么会收到(400)错误的请求错误?

[英]Why am I getting (400) Bad Request error when connecting to Text Analytics API?

I am new C# developer and I am trying to use Text Analytics API with Azure Machine Learning in my test ASP.NET application to define the sentiment and key phrases for the tweets I have in the database. 我是新的C#开发人员,我试图在我的测试ASP.NET应用程序中将Text Analytics API与Azure机器学习一起使用,以定义我在数据库中所具有的推文的情感和关键短语。 I followed this useful article over here to be able to connect to Text Analytics API. 在这里关注了这篇有用的文章能够连接到Text Analytics API。 While debugging my code, I was able to get the key phrases and sentiment for the first tweet in the list and then I got the following exception and I don't know why: 在调试代码时,我能够获得列表中第一条推文的关键短语和情感,然后得到以下异常,但我不知道为什么:

The remote server returned an error: (400) Bad Request. 远程服务器返回错误:(400)错误的请求。

Here's my code: 这是我的代码:

private const string apiKey = "XXXXXXXXX"; //Key 2 value of Text Analytics API from Azure Portal
        private const string sentimentUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
        private const string keyPhrasesUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";
        private const string languageUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages";

        protected void Page_Load(object sender, EventArgs e)
        {

        }


        private IEnumerable<T_Tweet> GetData()
        {
            TweetBL tweetBl = new TweetBL();
            IEnumerable<T_Tweet> tweetsList = tweetBl.GetTweets();
            return tweetsList;
        }


        protected void lbtnAnalyze_Click(object sender, EventArgs e)
        {
            var tweetsList = GetData();
            if (tweetsList != null)
            {
                List<TweetSentimentModel> tweetSenti = new List<TweetSentimentModel>();
                foreach (var tweet in tweetsList)
                {
                    try
                    {
                        // Prepare headers
                        var client = new WebClient();
                        client.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
                        client.Headers.Add("Content-Type", "application/json");
                        client.Headers.Add("Accept", "application/json");

                        // Detect language
                        var postData1 = @"{""documents"":[{""id"":""1"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText);
                        var response1 = client.UploadString(languageUri, postData1);
                        var language = new Regex(@"""iso6391Name"":""(\w+)""").Match(response1).Groups[1].Value;

                        // Determine sentiment
                        var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText).Replace("@language", language);
                        var response2 = client.UploadString(sentimentUri, postData2);
                        var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                        var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);

                        // Detemine key phrases
                        var postData3 = postData2;
                        var response3 = client.UploadString(keyPhrasesUri, postData2);
                        var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;


                        TweetSentimentModel tweetSentiObj = new TweetSentimentModel();
                        tweetSentiObj.TweetId = tweet.Id;
                        tweetSentiObj.TweetText = tweet.TweetText;
                        tweetSentiObj.SentimentLabel = sentiment.ToString();
                        tweetSentiObj.KeyPhrases = keyPhrases;
                        tweetSentiObj.CreatedOn = DateTime.Now;
                        tweetSenti.Add(tweetSentiObj);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                if (tweetSenti != null)
                {
                    PrintAnalysisResults(tweetSenti);
                }
            }
        }

Could you please tell me why I am getting this error and how I can fix it? 您能否告诉我为什么会收到此错误以及如何解决该错误?

I was able to get the key phrases and sentiment for the first tweet in the list and then I got the following exception and I don't know why: 我能够获得列表中第一条推文的关键短语和情感,然后出现以下异常,但我不知道为什么:

According to your description, the difference between second time and first time is the tweet object. 根据您的描述,第二次和第一次之间的区别是鸣叫对象。 And (400) Bad Request is also meaning that http request client paramters are not correct. 并且(400)错误的请求也意味着http请求客户端参数不正确。

I can repro it while tweet.TweetText equals null or tweet.TweetText.trim() equals string.empty. tweet.TweetText等于null或tweet.TweetText.trim()等于string.empty时,我可以对其进行复制。 在此处输入图片说明

Please have try to debug, if it is that case ,please have a try add logic to control it. 请尝试调试,如果是这种情况,请尝试添加逻辑来控制它。 The following is the demo code. 以下是演示代码。

if (!string.IsNullOrEmpty(tweet.TweetText?.Trim()))
  {
       // Determine sentiment
       var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace(
                            "@sampleText", tweet.TweetText).Replace("@language", language);
                    var response2 = client.UploadString(SentimentUri, postData2);
                    var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                    var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);

                    // Detemine key phrases
                    var postData3 = postData2;
                    var response3 = client.UploadString(KeyPhrasesUri, postData2);
                    var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WCF:为什么我总是收到400 Bad Request Error? - WCF: Why do I keep getting a 400 Bad Request Error? 我正在尝试使用 c# 从 Twitter api 获取请求令牌,但收到 400 个错误的请求错误 - I am trying to get request token from Twitter api using c#, but getting 400 bad request error 使用QuickBooks API时出现400错误 - I am getting a 400 error when using QuickBooks API Google Analytics Api 400错误请求 - Google Analytics Api 400 Bad Request 当我向Quickbooks添加新客户时,“远程服务器返回错误:(400)错误的请求。” - “remote server returned an error: (400) Bad Request.” when I am adding new Customer to Quickbooks.. 为什么我在使用 discord.net 的机器人上不断收到“错误请求:400”错误? - Why do I keep getting a “Bad Request: 400” error on my bot with discord.net? 部署更新API时如何解决400错误的错误请求 - How to resolve 400 error with bad request in update api when it is deployed 当我尝试使用 C# 在线使用 REST API 时收到错误请求状态代码 400 - I get a Bad request Status Code 400 when I am trying to consume a REST API online using C# 当我使用 JQuery.ajax() 方法将用户凭据发布到 C# controller 时,为什么会收到 HTTP 400(错误请求)错误? (ASP.NET Mvc 红隼) - Why I'm getting a HTTP 400 (bad request) error when I'm posting user credentials with JQuery .ajax() method, to a C# controller? (ASP.NET Mvc Kestrel) 使用Linkedin API时出现400错误的请求 - 400 bad request when using Linkedin api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM