簡體   English   中英

使用httpclient消費時出現無效URI錯誤

[英]Invalid URI Error when using httpclient to consume REST API

我正在嘗試使用以下代碼從 xamarin forms 應用程序中使用 REST API。 但是由於某些奇怪的原因,我收到了無效的 URI 錯誤。 我還嘗試在 PostAsync 方法中使用絕對路徑,但錯誤仍然存在。 有人可以指導我嗎?

HttpClient 客戶端 = 新 HttpClient(); string baseAdd = @"http://localhost:9000";

    public async void GenerateAPIToken()
    {

        string tsResult = "";
        try
        {

            Token token = new Token();
            //GET TOKEN
            client.BaseAddress = new Uri(baseAdd);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage msg = new HttpRequestMessage();
            msg.Content = new StringContent(@"{""username"":""admin"",""password"":""admin123""}");


            HttpResponseMessage response = await client.PostAsync(client.BaseAddress+"token/generate.php", msg.Content);


            if (response.StatusCode == HttpStatusCode.OK)
            {
                HttpContent cnt = response.Content;
                tsResult = await cnt.ReadAsStringAsync();
                token = JsonConvert.DeserializeObject<Token>(tsResult);
                App.apiToken = token.Document.AccessToken;
            }

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

謝謝

您已經指定了 BaseAddress

client.BaseAddress = new Uri(baseAdd);

所以你不需要在這里再做一次

HttpResponseMessage response = await client.PostAsync(client.BaseAddress+"token/generate.php", msg.Content);

相反,就這樣做

HttpResponseMessage response = await client.PostAsync("/token/generate.php", msg.Content);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM