Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Getting result of a task
Message
General information
Forum:
ASP.NET
Category:
Common Language Runtime
Environment versions
Environment:
C# 5.0
OS:
Windows 10
Database:
MS SQL Server
Miscellaneous
Thread ID:
01643645
Message ID:
01644068
Views:
69
The easiest way to use HttpWebRequest actually is to use WebClient() which is wrapper around it. Most operations are a single line although if you need to add authentication or headers it's a little more work.
WebClient client = new WebClient();
client.Headers.Set("Accept", "application/json");
client.Headers.Set("Content-Type", "application/json");

// this should handle basic auth
client.Credentials = new NetworkCredential("username", "password");

var resultJson = client.UploadString(url,json);
Another even easier way is to use Westwind.Utilities and you can do something like this:
       [TestMethod]
        public void JsonRequestTest()
        {
            var settings = new HttpRequestSettings()
            {
                Url = "http://codepaste.net/recent?format=json",
                Credentials = new NetworkCredential("username","Password")
            };
            var snippets = HttpUtils.JsonRequest<List<CodeSnippet>>(settings);

            Assert.IsNotNull(snippets);
            Assert.IsTrue(settings.ResponseStatusCode == System.Net.HttpStatusCode.OK);
            Assert.IsTrue(snippets.Count > 0);
            Console.WriteLine(snippets.Count);
        }
It handles the HTTP Call and JSON conversion for you in one shot.

+++ Rick ---

>Rick,
>
>I'm trying to find good examples of using HttpWebRequest.
>
>Say, I have the following method right now:
>
>
>private void SetRequestHeaders(string tcHost, string tcUserName, string tcPassword, int tnTimeout)
>        {
>            request = WebRequest.Create(tcHost) as HttpWebRequest;
>            request.Host = tcHost;
>            request.Headers.Remove("Accept");
>            request.Headers.Add("Accept", "application/json");
>            string authorizationKey = Convert.ToBase64String(
>             System.Text.ASCIIEncoding.ASCII.GetBytes(
>                 string.Format("{0}:{1}", tcUserName, tcPassword)));
>            request.Headers.Add("Authorization", "Basic " + authorizationKey);
>            request.Timeout = tnTimeout * 1000;
>        }
>
>This is the method I'd like to call before trying to get a response. The question is - my actual API url should be appened to the tcHost above. What should I do with the request variable above (assuming it's working - I haven't tested yet) to use the actual API url such as
>
>
>"/integrationapi//Attraction/Tickets/Validate"
>
>Thanks in advance.
>
>
>
>>If you're sending HTTP request synchronously I'd highly recommend you **don't** use HttpClient. Using the `.Result` property causes many issues and if you use it on a Web site you are very likely to lock up the application eventually when simultaneous requests are active hitting the same code.
>>
>>I'd recommend you just use WebClient() or HttpWebRequst() for synchronous HTTP requests, or if you want to use HttpClient() make sure you use Async/Await which requires that your calling method is async. Depending on what you call this code from this may be very easy to accomplish (like in an MVC controller you can just add `async` to the controller method and return a task (public async Task<ActionResul> MyMethod()).
>>
>>Whatever you do - stay away from using .Result with Async methods especially in Web applications - there are lots of issues there.
>>
>>+++ Rick ---
>>
>>
>>
>>>Hi everybody,
>>>
>>>I've defined the following method:
>>>
>>>
>>>static async Task<HttpResponseMessage> GetResponse(TicketUsageRequests ticket, string apiUrl)
>>>        {
>>>            HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, ticket);
>>>            //response.EnsureSuccessStatusCode();
>>>            
>>>            return response;
>>>        }
>>>
>>>My question is - how can I get its result in the main method code and synchronously?
>>>
>>>My current method is:
>>>
>>>
>>>try
>>>            {               
>>>                SetRequestHeaders(tcHost, tcUserName, tcPassword, tnTimeout, tnRetries);
>>>
>>>                TicketUsageRequests ticket = new TicketUsageRequests();
>>>                ticket.TicketBarcode = tcBarcode;
>>>                ticket.TicketUsageDate = tcUsageDate;
>>>                ticket.UserID = tcUserName;
>>>
>>>               ... here I want to get the result of the response and parse it
>>>
>>>   ...
>>>
>>>
>>>I found this
>>>
>>>http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously
>>>
>>>and trying to figure out how to apply pixel's solution.
>>>
>>>Thanks in advance.
+++ Rick ---

West Wind Technologies
Maui, Hawaii

west-wind.com/
West Wind Message Board
Rick's Web Log
Markdown Monster
---
Making waves on the Web

Where do you want to surf today?
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform