簡體   English   中英

發布到HTTP並在C#中獲取JSON響應

[英]Post to HTTP and get JSON response back in c#

我正在嘗試編寫一個調用網頁,然后將其發布到輸出JSON文件的Web服務。

我的問題是GetAsync返回一個空值作為響應。 反過來,這沒有提供正確的URL用於GetTestResultAsync方法的回調。

這是我的代碼:

    static HttpClient client = new HttpClient();

    static async Task RunAsync()
    {
        // New code:
        client.BaseAddress = new Uri("http://10.1.10.10:8080/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            Uri url = await CallTestAsync();

            string response = await GetTestResultAsync(url.PathAndQuery);

            Console.WriteLine(response);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    static async Task<Uri> CallTestAsync()
    {
        HttpResponseMessage response = await client.GetAsync("test.html");
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

    static async Task<string> GetTestResultAsync(string path)
    {
        HttpResponseMessage response = await client.GetAsync(path);
        string streamResponse = string.Empty;

        if (response.IsSuccessStatusCode)
        {
            streamResponse = await response.Content.ReadAsStringAsync();
        }
        return streamResponse;
    }

    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

默認情況下, HttpClient將自動重定向3xx響應,這意味着您在調用GetAsync時獲得的響應將沒有Location標頭,因為它已經被重定向到正確的位置。

要覆蓋此行為,您必須提供一個HttpMessageHandler了此功能的HttpMessageHandler 例如:

static HttpClientHandler handler = new HttpClientHandler { AllowAutoRedirect = false };
static HttpClient client = new HttpClient(handler);

重要的是將處理程序的AllowAutoRedirect設置為false

重要提示:通過覆蓋重定向響應的默認行為,您將必須手動處理任何3xx ,這可能為您增加不必要的工作,因為在許多情況下,默認行為就足夠了。 如果您將其保留原樣,它已經為您發出了第二個請求。

還要注意, 3xx響應不是成功響應 ,這意味着如果您在調用response.EnsureSuccessStatusCode();時不使用自動重定向功能response.EnsureSuccessStatusCode(); 它將引發異常

此外,盡管大多數服務器在使用諸如Accept標頭之類的標頭時都相當寬容,但在這種情況下,您很可能使用錯誤的標頭,因為HTML頁應該是text/html而不是application/json (在期望將JSON對象作為響應時使用)。

暫無
暫無

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

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