static void Main(string[] args) { SetLoggingEvents(); RestClient client = new RestClient("http://localhost:1234", null); RestRequest request = new RestRequest { Method = HttpMethod.GET, Resource = "foo/{id}", ContentType = ContentType.TextPlain }; request.AddParameter("id", "myId1"); request.AddQuery("location", "room"); request.AddQuery("location", "outside"); RestResponse response = client.SendRequest(request); WriteResponse(response); request.Resource = "ex/someException"; request.ClearQuery(); response = client.SendRequest(request); WriteResponse(response); Console.WriteLine("press any key"); Console.ReadLine(); }
private static void SetData(RestRequest restRequest, HttpWebRequest httpRequest) { byte[] data = restRequest.GetData(); httpRequest.ContentLength = data.Length; if (data.Length > 0) { using (Stream httpRequestStream = httpRequest.GetRequestStream()) { httpRequestStream.Write(data, 0, data.Length); } } }
/// <summary> /// todo all exceptions except WebException have to be handled by user /// </summary> public RestResponse SendRequest(RestRequest request) { string url = root + request.GetResourceAndQuery(); HttpWebRequest httpRequest = CreateHttpRequest(request, url); SetData(request, httpRequest); RestResponse response; try { HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); response = new RestResponse(httpResponse); this.Cookies.Add(httpResponse.Cookies); } catch (WebException ex) { response = new RestResponse(ex); } return response; }
private HttpWebRequest CreateHttpRequest(RestRequest restRequest, string url) { //cast to HttpWebRequest is needed for the CookieContainer and Credentials HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); httpRequest.Timeout = restRequest.Timeout; httpRequest.Method = restRequest.Method.ToString(); httpRequest.Headers = restRequest.Headers; httpRequest.ContentType = restRequest.ContentType.GetValue(); httpRequest.CookieContainer = Cookies; if (credentialsOrNull != null) { httpRequest.Credentials = credentialsOrNull; } return httpRequest; }