private static string GetXRequestDigestForPostRequest(SearchRequest searchRequest) { string digestValue = ""; var request = CreateWebRequest(searchRequest.GenerateHttpPostUri(), searchRequest.AcceptType, searchRequest.Timeout.HasValue ? searchRequest.Timeout.Value : SearchRequest.DefaultTimeout, searchRequest.AuthenticationType, searchRequest.SharePointSiteUrl, searchRequest.UserName, searchRequest.Password, searchRequest.SecurePassword, searchRequest.Cookies, searchRequest.Token); request.Method = "POST"; request.ContentType = "application/json;odata=verbose;charset=utf-8"; request.ContentLength = 0; try { using (var response = (request as HttpWebRequest).GetResponse() as HttpWebResponse) { foreach (var header in response.Headers.AllKeys) { if (header.ToLower() == "x-requestdigest") { digestValue = response.Headers[header]; break; } } } } catch (WebException webex) // expected 403 Forbidden { using (WebResponse response = webex.Response) { HttpWebResponse httpResponse = response as HttpWebResponse; if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.Forbidden) { foreach (var header in response.Headers.AllKeys) { if (header.ToLower() == "x-requestdigest") { digestValue = response.Headers[header]; break; } } } } } return(digestValue); }
private static HttpRequestResponsePair RunPostWebRequest(SearchRequest searchRequest) { string xrequestDigestValue = GetXRequestDigestForPostRequest(searchRequest); var request = CreateWebRequest(searchRequest.GenerateHttpPostUri(), searchRequest.AcceptType, searchRequest.Timeout.HasValue ? searchRequest.Timeout.Value : SearchRequest.DefaultTimeout, searchRequest.AuthenticationType, searchRequest.SharePointSiteUrl, searchRequest.UserName, searchRequest.Password, searchRequest.SecurePassword, searchRequest.Cookies, searchRequest.Token); request.Method = "POST"; request.ContentType = "application/json;odata=verbose;charset=utf-8"; request.Headers["x-requestdigest"] = xrequestDigestValue; string payload = searchRequest.GenerateHttpPostBodyPayload(); if (!String.IsNullOrEmpty(payload)) { byte[] bytes = Encoding.UTF8.GetBytes(payload); request.ContentLength = (long)bytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } HttpWebResponse response = null; try { response = request.GetResponse() as HttpWebResponse; } catch (WebException webEx) { response = webEx.Response as HttpWebResponse; } return(new HttpRequestResponsePair(request, response, payload)); }