简体   繁体   中英

Post to HTTP and get JSON response back in c#

I am trying to write call a web page that then posts to a web service that outputs a JSON file.

The problem I have is that the GetAsync returns a null value for response. This in turn doesn't provide the proper URL for call back for the GetTestResultAsync method.

Here's my code:

    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 by default will automatically redirect 3xx responses, which means that the response you get when calling GetAsync will not have the Location header as it would have already redirected to the proper location.

To override this behaviour you have to provide an HttpMessageHandler with this feature disabled. For example:

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

The important part here being setting the handler's AllowAutoRedirect to false .

Important: By overriding the default behaviour for redirect responses you'll have to handle any 3xx manually, which might add unnecessary work for you as in many cases the default behaviour is sufficient. If you were to leave it as is, it'd already make the 2nd request that you're doing, for you.

Also note that a 3xx response is not a success response , which means that if you don't use the auto-redirect feature when you call response.EnsureSuccessStatusCode(); it'll throw an exception .

Furthermore, although most servers are quite forgiving when it comes to headers such as the Accept header, you are most likely using the wrong one in this case as an HTML page should be a text/html rather than an application/json (which should be used when expecting a JSON object as a response).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM