コード例 #1
0
        /// <summary>
        /// Invoke "POST" HTTP request to API
        /// </summary>
        /// <returns>Return resulst as string in UTF8 format</returns>
        public String InvokePost()
        {
            AddPostRequiredParams();
            String parameters = JoinParameters();

            //create http content for POST request
            HttpContent httpContent = HttpContent.Create(parameters, "application/x-www-form-urlencoded");
            String      result;

            try
            {
                using (HttpClient httpClient = new HttpClient(_apiHost))
                {
                    HttpResponseMessage httpResponseMessage = httpClient.Post(_requestUrl, httpContent);

                    Byte[] data = httpResponseMessage.Content.ReadAsByteArray();
                    result = Encoding.UTF8.GetString(data);
                }
            }
            catch (Exception)
            {
                //TODO: log
                throw;
            }

            return(result);
        }
コード例 #2
0
        public void UploadFile()
        {
            using (var client = new HttpClient())
            {
                var fileName = tbFilePath.Text;
                var strUrl   = tbUrl.Text;
                client.DefaultHeaders.Add(tbIdKey.Text, tbAppId.Text);
                var sign = PercentEncoding.GenerateSignature(tbUrl.Text, "post", GetFileBase64(), tbAppSecurity.Text);
                client.DefaultHeaders.Add(tbAppSecretyKey.Text, sign);

                var content = HttpContent.Create(File.OpenRead(fileName));
                try
                {
                    var response = client.Post(strUrl, content);
                    response.EnsureStatusIsSuccessful();
                    var readResult = response.Content.ReadAsString();
                    tbResult.Text = readResult;
                }
                catch (Exception exp)
                {
                    tbResult.Text = exp.Message;
                }
                finally
                {
                    content.Dispose();
                }
            }
        }
コード例 #3
0
        private static string UploadFile(FileInfoEntity entity)
        {
            string       errorMsg  = null;
            IFormatter   formatter = new BinaryFormatter();
            MemoryStream ms        = new MemoryStream();

            formatter.Serialize(ms, entity);
            ms.Position = 0;

            var content = HttpContent.Create(ms, "application/octet-stream", ms.Length);
            var client  = new HttpClient();

            using (var response = client.Post(uploadUri, content))
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    response.Content.LoadIntoBuffer();
                }
                else
                {
                    errorMsg = response.Content.ReadAsString();
                    Regex rg = new Regex(@"<P><B>Details[::][\s]*<\/B>([^\/]+)</P>");
                    if (rg.Match(errorMsg).Success)
                    {
                        errorMsg = rg.Match(errorMsg).Result("$1");
                    }
                }
            }
            return(errorMsg);
        }
コード例 #4
0
ファイル: ClientHelper.cs プロジェクト: 786744873/WCFPractise
        public static HttpContent CreateContent(User u)
        {
            var con  = JsonConvert.SerializeObject(u);
            var data = System.Text.Encoding.UTF8.GetBytes(con);

            return(HttpContent.Create(data, "application/json"));
        }
コード例 #5
0
        /// <summary>
        /// Creates or updates a given file resource in the file system in one blocking operation.
        /// </summary>
        /// <param name="virtualFilePath">The qualified path of the file to be created.</param>
        /// <param name="input">A stream that provides the file's contents.</param>
        /// <param name="overwrite">Whether an existing file should be overwritten
        /// or not. If this parameter is false and the file already exists, a
        /// <see cref="ResourceOverwriteException"/> is thrown.</param>
        /// <param name="resourceLength">The length of the resource to be uploaded in bytes.</param>
        /// <param name="contentType">The content type of the uploaded resource.</param>
        /// <exception cref="ResourceAccessException">In case of invalid or prohibited
        /// resource access.</exception>
        /// <exception cref="ResourceOverwriteException">If a file already exists at the
        /// specified location, and the <paramref name="overwrite"/> flag was not set.</exception>
        /// <exception cref="ArgumentNullException">If any of the parameters is a null reference.</exception>
        public void WriteFile(string virtualFilePath, Stream input, bool overwrite, long resourceLength, string contentType)
        {
            string actionUri = VfsUris.Default.WriteFileContentsUri;

            actionUri = actionUri.ConstructUri(Uris.PatternFilePath, virtualFilePath);

            //set headers
            RequestHeaders requestHeader = new RequestHeaders();
            VfsHttpHeaders headers       = VfsHttpHeaders.Default;

            requestHeader.Add(headers.OverwriteExistingResource, overwrite.ToString(CultureInfo.InvariantCulture));
            requestHeader.Add("Content-Length", resourceLength.ToString(CultureInfo.InvariantCulture));
            requestHeader.Add("Content-Type", contentType);


            Func <HttpClient, HttpResponseMessage> func = c =>
            {
                HttpContent content = HttpContent.Create(() => input);
                return(c.Send(HttpMethod.POST, actionUri, requestHeader,
                              content));
            };

            SecureRequest(FileSystemTask.StreamedFileUploadRequest,
                          func,
                          () => String.Format("Could not write data for file [{0}] to file system.", virtualFilePath));
        }
コード例 #6
0
        /// <summary>
        /// 获取PJSON
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private HttpContent GetJsonContent(object t)
        {
            var strContent = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            var data       = Encoding.UTF8.GetBytes(strContent);

            return(HttpContent.Create(data, "application/json"));
        }
コード例 #7
0
        /// <summary>
        /// Post数据到指定Url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestBody"></param>
        /// <param name="headers"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public string PostDataTo(string url, string requestBody, Dictionary <string, string> headers = null, TimeSpan?timeOut = null)
        {
            using (var client = new HttpClient())
            {
                client.DefaultHeaders.Add("Content-Type", "application/json");
                client.DefaultHeaders.Add("Accept", "application/json");
                AppendHttpHeader(client, headers);
                client.TransportSettings.ConnectionTimeout = timeOut.HasValue ? timeOut : RestTimeOut;
                var data        = Encoding.UTF8.GetBytes(requestBody);
                var postContent = HttpContent.Create(data, "application/json");
                var response    = client.Post(url, postContent);
                var content     = response.Content.ReadAsString();

                //LoggerFactory.CreateLog().LogInfo("Request to {0} using methord(Post) with body {1} and Response is {2}.", url, string.IsNullOrEmpty(requestBody) ? "" : requestBody, content);
                try
                {
                    response.EnsureStatusIsSuccessful();
                }
                catch (Exception e)
                {
                    throw new Exception(content, e);
                }
                return(content);
            }
        }
コード例 #8
0
        /// <summary>
        /// Insert 按钮单击事件处理例程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsert_Click(object sender, EventArgs e)
        {
            String strName   = txtName.Text.Trim();
            String strPwd    = txtPwd.Text.Trim();
            String strSvcURI = BASE_USER_SERVICE + "User/Insert";

            if (String.IsNullOrEmpty(strName) || String.IsNullOrEmpty(strPwd))
            {
                MessageBox.Show("  UserName Or User Password Error !  ", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            String   strSex  = cbBoxSex.SelectedItem.ToString();
            DateTime dtBirth = dtpBirth.Value;

            UserEntity entity = new UserEntity();

            entity.UserName     = strName;
            entity.UserPassword = strPwd;
            entity.UserSex      = strSex;
            entity.UserBirth    = dtBirth;
            entity.CreateDate   = DateTime.Now;

            String strContent = JsonConvert.SerializeObject(entity);
            //Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strContent);
            HttpContent content = HttpContent.Create(strContent, "application/json");

            HttpClient          client      = new HttpClient();
            HttpResponseMessage responseMsg = client.Post(strSvcURI, content);

            responseMsg.EnsureStatusIsSuccessful();
        }
コード例 #9
0
        private static HttpResponseMessage GetResponse(string url, HttpMethod method, string parameters)
        {
            var client = new SitefinityClient();

            client.RequestAuthenticate();
            var request = new HttpRequestMessage(method.ToString(), url);

            switch (method)
            {
            case HttpMethod.POST:
                request.Headers.ContentType = "application/x-www-form-urlencoded";
                break;

            case HttpMethod.PUT:
                request.Headers.ContentType = "text/json";
                break;
            }

            if (parameters != null)
            {
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
                request.Headers.ContentLength = bytes.Length;
                request.Content = HttpContent.Create(bytes);
            }

            client.TransportSettings.MaximumAutomaticRedirections = 5;
            var response = client.Send(request);

            return(response);
        }
コード例 #10
0
        /// <summary>
        /// Posts the data of a given data block to the server.
        /// </summary>
        private HttpResponseMessage SendDataBlock(HttpClient client, StreamedDataBlock dataBlock)
        {
            string actionUri = VfsUris.Default.WriteStreamedDataBlockUri;

            actionUri = actionUri.ConstructUri(Uris.PatternTransferId, dataBlock.TransferTokenId);
            actionUri = actionUri.ConstructUri(Uris.PatternBlockNumber, dataBlock.BlockNumber.ToString(CultureInfo.InvariantCulture));

            RequestHeaders requestHeader = new RequestHeaders();

            //write the HTTP headers
            VfsHttpHeaders headers = VfsHttpHeaders.Default;

            requestHeader.Add(headers.TransferId, dataBlock.TransferTokenId); //duplicate transfer ID, might be useful in some scenarios
            requestHeader.Add(headers.BlockNumber, dataBlock.BlockNumber.ToString());
            requestHeader.Add(headers.IsLastBlock, Convert.ToString(dataBlock.IsLastBlock).ToLowerInvariant());
            requestHeader.Add(headers.BlockOffset, dataBlock.Offset.ToString());

            if (dataBlock.BlockLength.HasValue)
            {
                requestHeader.Add(headers.BlockLength, dataBlock.BlockLength.ToString());
            }

            using (dataBlock.Data)
            {
                return(client.Send(HttpMethod.POST, actionUri, requestHeader, HttpContent.Create(() => dataBlock.Data)));
            }
        }
コード例 #11
0
        private void CreateRequest(string requestType)
        {
            string server;
            string service;

            if (localCheckBox.Checked)
            {
                server = Properties.Settings.Default.LocalAdress;
            }
            else
            {
                server = Properties.Settings.Default.RemoteAdress;
            }
            if (!string.IsNullOrEmpty(QueryStringstextBox.Text.Trim()) && Regex.Matches(ServiceAddressComboBox.Text, "{\\d}").Count > 0)
            {
                string[] queryStringsArray = QueryStringstextBox.Text.Split(',');
                service = string.Format(ServiceAddressComboBox.Text, queryStringsArray);
            }
            else
            {
                service = ServiceAddressComboBox.Text.Trim();
            }


            string fullAddress = string.Format("http://{0}/{1}", server, service);

            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(requestType, fullAddress);

            //Microsoft.Http.Headers.Connection conn = new Microsoft.Http.Headers.Connection() { Close = false };
            request.Headers.Accept.Add(new Microsoft.Http.Headers.StringWithOptionalQuality("application/json"));



            foreach (ListViewItem item in HeaderslistView.Items)
            {
                request.Headers.Add(item.Text, item.SubItems[1].Text);
            }
            if (requestType == "POST" || requestType == "PUT")
            {
                request.Headers.ContentType = "application/json";
                if (!string.IsNullOrEmpty(BodyTextBox.Text))
                {
                    request.Content = HttpContent.Create(BodyTextBox.Text);
                }
            }
            HttpResponseMessage response = new HttpResponseMessage();

            response.Headers.ContentType = "application/json";
            response = client.Send(request);
            ResponseHeaderTextBox.Text  = string.Empty;
            ResponseHeaderTextBox.Text += response.StatusCode + "\n";
            foreach (KeyValuePair <string, string[]> header in response.Headers)
            {
                ResponseHeaderTextBox.Text += string.Format(header.Key + ": {0}\n", header.Value[0]);
            }
            ResponseBodyRichTextBox.Text = response.Content.ReadAsString();
            AfterRespondEvents(service);
        }
コード例 #12
0
        public override void ProcessResponse(ref System.ServiceModel.Channels.Message request, ref System.ServiceModel.Channels.Message response)
        {
            // Don't do anything if there was no error
            Exception ex = null;

            if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(StatusCodeProperty))
            {
                return;
            }

            HttpStatusCode statusCode = (HttpStatusCode)OperationContext.Current.OutgoingMessageProperties[StatusCodeProperty];
            //object error = OperationContext.Current.OutgoingMessageProperties[ErrorObjectProperty];

            // TODO: add text message to output
            HttpResponseMessage responseMessage = request.ToHttpRequestMessage().CreateResponse(statusCode);



            //var httpMessageProperty = OperationContext.Current.IncomingMessageProperties[HttpMessageProperty.Name] as HttpMessageProperty;
            //var httpRequest = httpMessageProperty.Request as HttpRequestMessage;
            var httpRequest          = request.ToHttpRequestMessage();
            var endpoint             = OperationContext.Current.Host.Description.Endpoints.Find(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri);
            var uriMatch             = httpRequest.Properties.First(p => p.GetType() == typeof(UriTemplateMatch)) as UriTemplateMatch;
            var dispatchOperation    = OperationContext.Current.EndpointDispatcher.DispatchRuntime.Operations.Where(op => op.Name == uriMatch.Data).First();
            var operationDescription = endpoint.Contract.Operations.Find(dispatchOperation.Name);
            var httpBehavoir         = endpoint.Behaviors.Find <HttpEndpointBehavior>();
            var processors           = httpBehavoir.GetResponseProcessors(operationDescription.ToHttpOperationDescription()).ToList <Processor>();

            foreach (var processor in processors)
            {
                var mediaTypeProcessor = processor as MediaTypeProcessor;
                if (mediaTypeProcessor == null)
                {
                    continue;
                }

                if (mediaTypeProcessor.SupportedMediaTypes.Contains <string>("application/json"))
                {
                    ErrorObject errorObject = new ErrorObject()
                    {
                        ErrorCode = -1, Message = OperationContext.Current.OutgoingMessageProperties[ErrorObjectProperty].ToString(), StatusCode = Convert.ToInt32(OperationContext.Current.OutgoingMessageProperties[StatusCodeProperty])
                    };

                    if (ex != null)
                    {
                        errorObject.Ex = ex;
                    }


                    responseMessage.Content = HttpContent.Create(s => mediaTypeProcessor.WriteToStream(errorObject, s, httpRequest));
                    break;
                }
            }



            //	responseMessage.Content = HttpContent.Create( OperationContext.Current.OutgoingMessageProperties[ErrorObjectProperty].ToString() , "application/json");
            response = responseMessage.ToMessage();
        }
コード例 #13
0
        private HttpResponseMessage Post(string uri, string jsondata)
        {
            HttpResponseMessage response = _httpClient.Send(HttpMethod.POST,
                                                            uri,
                                                            HttpContent.Create(jsondata, "application/json"));

            return(response);
        }
コード例 #14
0
ファイル: TestHttpClient.cs プロジェクト: consumentor/Server
        public static HttpContent CreateJsonDataContract <T>(T value)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            StringBuilder        sb   = new StringBuilder();

            json.Serialize(value, sb);
            return(HttpContent.Create(sb.ToString(), Encoding.UTF8, "application/json"));
        }
コード例 #15
0
        public ReallySimpleRestClient.Http.DataPackets.HttpResponseMessage Send(string method, Uri uri, byte[] postData, string contentType)
        {
            var content  = HttpContent.Create(postData, contentType);
            var request  = new HttpRequestMessage(method, uri, content);
            var response = _httpClient.Send(request);

            return(ToNativeResponse(response));
        }
コード例 #16
0
ファイル: BaseRepository.cs プロジェクト: rotovibe/engage
        public HttpContent ConvertDictionaryToHttpContent(Dictionary <string, string> dictionary)
        {
            MemoryStream    stream    = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, dictionary);
            byte[] b = stream.ToArray();
            return(HttpContent.Create(b, "application/octet-stream"));
        }
コード例 #17
0
        public void ShouldNotThrowWhenTrueReturnedFromResponse()
        {
            OkHttpResponse.Content = HttpContent.Create("true");
            MockedHttpClientAdapter.Setup(hca => hca.GetHttpClient(It.IsAny <string>())).Returns(MockedHttpClient.Object);
            MockedHttpClient.Setup(hc => hc.Get(It.IsAny <string>())).Returns(OkHttpResponse);

            TestDelegate methodThatShouldThrow = () => PackageAuthenticator.EnsureKeyCanAccessPackage("key", "packageId", "packageVersion");

            Assert.DoesNotThrow(methodThatShouldThrow, "Should not have thrown when reponse returned true.");
        }
コード例 #18
0
        public void MoviesUnsupportedMediaTypeJson()
        {
            HttpContent content = HttpContent.Create(new MemoryStream(new byte[] { 1, 2, 3 }), "foo", null);

            using (HttpResponseMessage response = client.Post("Movies", content, "application/json"))
            {
                Assert.AreEqual(HttpStatusCode.UnsupportedMediaType, response.StatusCode);
                Assert.AreEqual("application/json; charset=utf-8", response.Content.ContentType);
            }
        }
コード例 #19
0
        public void ShouldThrowWhenReturnedContentIsNotABoolean()
        {
            OkHttpResponse.Content = HttpContent.Create("not a bool");
            MockedHttpClientAdapter.Setup(hca => hca.GetHttpClient(It.IsAny <string>())).Returns(MockedHttpClient.Object);
            MockedHttpClient.Setup(hc => hc.Get(It.IsAny <string>())).Returns(OkHttpResponse);

            TestDelegate methodThatShouldThrow = () => PackageAuthenticator.EnsureKeyCanAccessPackage("key", "packageId", "packageVersion");

            Assert.Throws <PackageAuthorizationException>(methodThatShouldThrow, "Should have thrown when reponse returned non-boolean.");
        }
コード例 #20
0
        public void SendAsync(string method, Uri uri, byte[] postData, string contentType, Action <ReallySimpleRestClient.Http.DataPackets.HttpResponseMessage> httpClientCallback)
        {
            var content        = HttpContent.Create(postData, contentType);
            var request        = new HttpRequestMessage(method, uri, content);
            var rawRequestData = new AsyncRequest {
                RawPostData = postData, RawPostDataContentType = contentType, HttpClientCallback = httpClientCallback
            };

            _httpClient.BeginSend(request, SendAsyncEnd, rawRequestData);
        }
コード例 #21
0
        public ReallySimpleRestClient.Http.DataPackets.HttpResponseMessage Send(string method, Uri uri, ReallySimpleRestClient.Http.DataPackets.HttpContent postData)
        {
            System.Diagnostics.Debug.WriteLine("Request: " + uri.ToString() + " (" + method + ")");
            var httpRequestMessage = new HttpRequestMessage(method, uri, HttpContent.Create(postData.Content, postData.ContentType))
            {
                Headers = { ContentType = postData.ContentType }
            };
            var response = _httpClient.Send(httpRequestMessage);

            return(ToNativeResponse(response));
        }
コード例 #22
0
        public void SendAsync(string method, Uri uri, ReallySimpleRestClient.Http.DataPackets.HttpContent postData, Action <ReallySimpleRestClient.Http.DataPackets.HttpResponseMessage> httpClientCallback)
        {
            var httpRequestMessage = new HttpRequestMessage(method, uri, HttpContent.Create(postData.Content, postData.ContentType))
            {
                Headers = { ContentType = postData.ContentType }
            };
            var rawRequestData = new AsyncRequest {
                PostData = postData, HttpClientCallback = httpClientCallback
            };

            _httpClient.BeginSend(httpRequestMessage, SendAsyncEnd, rawRequestData);
        }
コード例 #23
0
        /// <summary>
        /// Make Authenticate PUT Request
        /// </summary>
        /// <param name="url">The web request url </param>
        /// <param name="payload">The payload of the request</param>
        public void MakeAuthenticatePutRequest(string url, string payload)
        {
            var client = new SitefinityClient();

            client.RequestAuthenticate();
            var request = new HttpRequestMessage("put", url);

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(payload);
            request.Headers.ContentType   = "text/json";
            request.Headers.ContentLength = bytes.Length;
            request.Content = HttpContent.Create(bytes);
            client.Send(request);
        }
コード例 #24
0
        public void SetUp()
        {
            MockedHttpClientAdapter = new Mock <IHttpClientAdapter>();
            MockedHttpClient        = new Mock <IHttpClient>();
            MockedConfigSettings    = new Mock <IConfigSettings>();

            PackageAuthenticator = new Infrastructure.Impl.PackageAuthenticator(MockedHttpClientAdapter.Object, MockedConfigSettings.Object,
                                                                                new Mock <ILogger>().Object);

            OkHttpResponse = new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK, Content = HttpContent.Create("true")
            };
        }
コード例 #25
0
        public void MoviesUnsupportedMediaTypeXml()
        {
            client.DefaultHeaders.Add(psuedoAuthHeaderForBob);

            HttpContent content = HttpContent.Create(new MemoryStream(new byte[] { 1, 2, 3 }), "foo", null);

            using (HttpResponseMessage response = client.Post("AuthHome/create", content, "application/xml"))
            {
                Assert.AreEqual(HttpStatusCode.UnsupportedMediaType, response.StatusCode);
                Assert.AreEqual("application/xml; charset=utf-8", response.Content.ContentType);
            }

            client.DefaultHeaders.Remove(psuedoAuthHeaderForBob);
        }
コード例 #26
0
ファイル: SkyDrive.cs プロジェクト: techienickb/hap
        public static void UploadFileToSkydrive(FileInfo file, string accessToken)
        {
            string uploaduri = string.Format("https://apis.live.net/v5.0/me/skydrive/files/{0}?access_token={1}",
                                             file.Name, accessToken);

            HttpClient httpClient = new HttpClient();

            if (!string.IsNullOrEmpty(hapConfig.Current.ProxyServer.Address) && hapConfig.Current.ProxyServer.Enabled)
            {
                httpClient.TransportSettings.Proxy = new WebProxy(hapConfig.Current.ProxyServer.Address, hapConfig.Current.ProxyServer.Port);
            }

            HttpContent c = HttpContent.Create(file.OpenRead());

            HttpResponseMessage response = httpClient.Put(uploaduri, c);
        }
コード例 #27
0
ファイル: ImgForm.cs プロジェクト: wzugang/RESTful
        /// <summary>
        /// Insert 按钮单击事件处理例程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == openFileDlg.ShowDialog())
            {
                String strFilePath = openFileDlg.FileName;
                String strFileName = Path.GetFileName(strFilePath);

                String strSvcURI = String.Format("{0}Image/Insert/{1}", BASE_IMAGE_SERVICE, strFileName);

                HttpClient  client  = new HttpClient();
                HttpContent content = HttpContent.Create(File.OpenRead(strFilePath));

                HttpResponseMessage responseMsg = client.Post(strSvcURI, content);
                responseMsg.EnsureStatusIsSuccessful();

                BindAllImageName();
            }
        }
コード例 #28
0
        public void CrudMoviesForm()
        {
            string       director     = "Reiner";
            string       title        = "This is Spinal Tap";
            DateTime     dateReleased = new DateTime(1984, 4, 2);
            List <Movie> originalMovieList;
            List <Movie> updatedMovieList;

            client.DefaultHeaders.Add(psuedoAuthHeaderForBob);

            using (HttpResponseMessage response = client.Get("AuthHome", "application/xml"))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                originalMovieList = response.Content.ReadAsDataContract <List <Movie> >();
            }

            using (HttpResponseMessage response = client.Post("AuthHome/create", HttpContent.Create(new HttpUrlEncodedForm()
            {
                { "Director", director }, { "Title", title }, { "DateReleased", dateReleased.ToString() }
            })))
            {
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            }

            using (HttpResponseMessage response = client.Get("AuthHome", "application/xml"))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >();
            }

            Movie insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault();

            Assert.IsNotNull(insertedMovie);
            Assert.AreEqual(director, insertedMovie.Director);
            Assert.AreEqual(title, insertedMovie.Title);
            Assert.AreEqual(dateReleased, insertedMovie.DateReleased);

            using (HttpResponseMessage response = client.Delete("AuthHome/delete/" + insertedMovie.Id.ToString()))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
            client.DefaultHeaders.Remove(psuedoAuthHeaderForBob);
        }
コード例 #29
0
        /// <summary>
        /// 创建一个用于封装提交数据的HttpContent
        /// </summary>
        /// <typeparam name="TEntity">要提交的实体数据类型</typeparam>
        /// <param name="entity">要提交的数据实体对象</param>
        /// <param name="encoding">设置提交数据的编码格式</param>
        /// <param name="contentType">设置提交数据的类型</param>
        /// <returns>返回封装好的HttpContent对象</returns>
        public virtual HttpContent CreateHttpContent <TEntity>(TEntity entity, Encoding encoding, string contentType)
            where TEntity : class
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (string.IsNullOrWhiteSpace(contentType))
            {
                throw new ArgumentNullException("contentType");
            }

            string request = "";

            if (contentType == MimeType.JSON)
            {
                JsonSerializerSettings settings = GetJsonSettings();
                request = JsonConvert.SerializeObject(entity, settings);
            }
            else if (contentType == MimeType.XML)
            {
                XmlSerializer xml       = new XmlSerializer(typeof(TEntity));
                StringBuilder xmlString = new StringBuilder();
                using (TextWriter writer = new StringWriter(xmlString))
                {
                    xml.Serialize(writer, entity);
                }
                request = xmlString.ToString();
            }
            byte[] stream = encoding.GetBytes(request);
            return(HttpContent.Create(stream, contentType));
        }
コード例 #30
0
        public void CrudMoviesFormBrowser()
        {
            string       director     = "Reiner";
            string       title        = "This is Spinal Tap";
            DateTime     dateReleased = new DateTime(1984, 4, 2);
            List <Movie> originalMovieList;
            List <Movie> updatedMovieList;

            client.DefaultHeaders.Add(psuedoAuthHeaderForBob);

            using (HttpResponseMessage response = client.Get("AuthHome", "application/xml"))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                originalMovieList = response.Content.ReadAsDataContract <List <Movie> >();
            }

            using (HttpRequestMessage request = new HttpRequestMessage("POST", new Uri("AuthHome/create", UriKind.RelativeOrAbsolute), HttpContent.Create(new HttpUrlEncodedForm()
            {
                { "Director", director }, { "Title", title }, { "DateReleased", dateReleased.ToString() }
            })))
            {
                // query string is only available to browsers, pretend we're a browser
                request.Headers.UserAgent.Add(TestHttpClient.Mozilla40);
                using (HttpResponseMessage response = client.Send(request))
                {
                    Assert.AreEqual(HttpStatusCode.Found, response.StatusCode);
                }
            }
            using (HttpResponseMessage response = client.Get("AuthHome", "application/xml"))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                updatedMovieList = response.Content.ReadAsDataContract <List <Movie> >();
            }

            Movie insertedMovie = updatedMovieList.Except(originalMovieList, moviesComparer).SingleOrDefault();

            Assert.IsNotNull(insertedMovie);
            Assert.AreEqual(director, insertedMovie.Director);
            Assert.AreEqual(title, insertedMovie.Title);
            Assert.AreEqual(dateReleased, insertedMovie.DateReleased);

            using (HttpResponseMessage response = client.Delete("AuthHome/delete/" + insertedMovie.Id.ToString()))
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
            client.DefaultHeaders.Remove(psuedoAuthHeaderForBob);
        }