Send() public méthode

public Send ( HttpMethod method ) : HttpResponseMessage
method HttpMethod
Résultat HttpResponseMessage
        static HttpResponseMessage Method(HttpClient client, HttpMethod method, Uri uri, HttpContent body)
        {
            CheckNull(client, "client");
            CheckNull(uri, "uri");
            CheckNull(body, "body");

            return(client.Send(method, uri, body));
        }
Exemple #2
0
        public override void Run(TestContainer container)
        {
            try
            {
                var jsonResult = String.Empty;
                var target     = base.GetParameter("Target");
                var methodType = base.GetParameter(@"MethodType").ToUpper();
                var jsonHeader = base.GetParameter(@"Header");
                var jsonBody   = base.GetParameter(@"Body");



                using (Microsoft.Http.HttpClient client = new Microsoft.Http.HttpClient())
                {
                    var headers = JsonConvert.DeserializeObject <Dictionary <String, String> >(jsonHeader);
                    client.DefaultHeaders.Add("Content-Type", "application/json");
                    foreach (KeyValuePair <string, string> item in headers)
                    {
                        client.DefaultHeaders.Add(item.Key, item.Value);
                    }
                    var content = Microsoft.Http.HttpContent.Create(jsonBody.Replace(@"'", @""""));

                    HttpMethod          httpMethod      = (HttpMethod)Enum.Parse(typeof(HttpMethod), methodType);
                    HttpResponseMessage responseMessage = client.Send(httpMethod, new Uri(target), client.DefaultHeaders, content);
                    var stringContent = responseMessage.Content.ReadAsString();
                    var statusCode    = responseMessage.StatusCode;
                    this.PassTest = statusCode == System.Net.HttpStatusCode.OK ? true : false;
                    if (this.PassTest == false)
                    {
                        throw (new Exception(String.Format(@"uri:{0}, methodType:{1}, statusCode:{2}, response message:{3}.", target, methodType, statusCode, stringContent)));
                    }

                    if (string.IsNullOrEmpty(this.Output.Key) == false)
                    {
                        if (String.IsNullOrEmpty(stringContent))
                        {
                            this.Output = new KeyValuePair <String, Tuple <Type, String> >(this.Output.Key, new Tuple <Type, String>(typeof(String), String.Empty));
                        }
                        else
                        {
                            stringContent = stringContent.Trim();
                            if (stringContent.StartsWith("[") == false && stringContent.EndsWith("[") == false)
                            {
                                stringContent = "[" + stringContent + "]";
                                JsonConvert.DeserializeObject <List <Dictionary <String, String> > >(stringContent);
                            }
                            this.Output = new KeyValuePair <String, Tuple <Type, String> >(this.Output.Key, new Tuple <Type, String>(typeof(List <Dictionary <String, String> >), stringContent));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
        }
        static HttpResponseMessage Method(HttpClient client, HttpMethod method, Uri uri, string contentType, HttpContent body)
        {
            CheckNull(client, "client");
            CheckNull(uri, "uri");
            CheckNull(body, "body");
            CheckNull(body, "contentType");

            return(client.Send(method, uri, new RequestHeaders()
            {
                ContentType = contentType
            }, body));
        }
Exemple #4
0
        static void ListAllContacts()
        {
            using (HttpClient client = new HttpClient("http://localhost:9000/api/contacts/"))
            {
                //Get
                Console.WriteLine("Get-Method Test...");
                using (var request = new HttpRequestMessage("GET", "Get/1/name"))
                {
                    request.Headers.Accept.Add("application/json");

                    using (var response = client.Send(request))
                    {
                        var status = response.StatusCode;
                        Console.WriteLine("Status Code: {0}", status);
                        var result = response.Content.ReadAsString();
                        Console.WriteLine("Content: {0}", result);
                    }
                }
                //Post
                Console.WriteLine("Post-Method Test...");
                HttpContent content = HttpContentExtensions
                    .CreateJsonDataContract(new List<Contact>
                                                {
                                                    new Contact{Name = "王春雷"},
                                                    new Contact{ContactId = 1,Name = "老张"}
                                                });
                content.LoadIntoBuffer();

                using (var response = client.Put("Filter/1/王春雷", content))
                {
                    response.EnsureStatusIsSuccessful();
                    response.Content.LoadIntoBuffer();

                    var result = response.Content.ReadAsJsonDataContract<List<Contact>>();
                    //var serializer = new JavaScriptSerializer();
                    //var con=serializer.Deserialize<List<Contact>>(result);
                    result.ForEach(r => Console.WriteLine(r.ToString()));
                }
            }
            Console.ReadKey();
        }
        public void GetProductsWithQueryStringRelative()
        {
            var serializer = new XmlSerializer(typeof(Crawler.Model.LinkShare.result));

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://feed.linksynergy.com");

            HttpQueryString query = new HttpQueryString();
            query.Add("token", "5bfb339580a02308573204c2ac1bb921ecba09ba542a19d271c2d7e9c27a509f");
            query.Add("keyword", "DVD Player");
            query.Add("Page", "1");
            query.Add("MaxResults", "100");

            var uri = HttpQueryString.MakeQueryString(new Uri("/productsearch?", UriKind.Relative), query);
            var req = new HttpRequestMessage("GET", uri);

            using (var response = client.Send(req))
            {
                //string results = response.Content.ReadAsString();
                var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
            }
        }
        public void GetProductsWithQueryStringRelative()
        {
            var serializer = new XmlSerializer(typeof(Crawler.Model.CJ.cjapi));

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://product-search.api.cj.com");

            HttpQueryString query = new HttpQueryString();
            query.Add("website-id", "3100204");
            query.Add("keywords", "DVD");
            query.Add("page-number", "1");
            query.Add("records-per-page", "1000");

            var uri = HttpQueryString.MakeQueryString(new Uri("/v2/product-search?", UriKind.Relative), query);
            var req = new HttpRequestMessage("GET", uri);
            req.Headers.Add("authorization", "00b171e48c4bc1e70836b252e1c4c40a893f19db0457be8447b1acdbdc0e7e769e1b804c1af54f883326d6147d1365f4b5f031a61740cf0c63a9f4b3d174cebbbf/420a385c3aa9bcd962b9f57ccf2583225758c11999aa6f42db8e90f9126fe0a7110790cd2ccd66a4f1861e89bd33fcfa6f528b494fa183f5d380ca289d18c309");

            using (var response = client.Send(req))
            {
                //string results = response.Content.ReadAsString();
                var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
            }
        }
Exemple #7
0
        /// <summary>
        /// Static method to request a webservice and get the response content
        /// </summary>
        /// <param name="service">Request Object</param>
        /// <returns>Response Object</returns>
        public static HttpResponseMessage ExecuteServiceMethod(WebServiceUrl service, string userName, string password)
        {
            HttpResponseMessage response = null;
            isOem = service.IsOem;

            try
            {
                using (var webClient = new HttpClient())
                {
                    webClient.DefaultHeaders.Add("Content-Type", "application/xml;charset=utf-8");
                    webClient.DefaultHeaders.Add("Authorization", GetAuthHeader(userName, password));

                    if (service.Method == HttpMethod.POST)
                    {
                        response = webClient.Send(service.Method, service.Url,
                            HttpContent.Create(requestHeader + service.Request, "application/xml"));

                    }
                    else
                    {
                        if (service.Request != null && service.Request.ToString().Length > 0)
                        {
                            service.Url += string.Format("/{0}", service.Request.ToString());
                        }
                        response = webClient.Get(service.Url);
                    }
                }
            }
            catch (Exception e)
            {
                TextLog.LogMessage("Faile to request the web service with the exception : " + e.Message);
                throw ;
            }

            return response;
        }
Exemple #8
0
        protected override void ExecuteTask()
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();

            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                client.DefaultHeaders.Authorization = Credential.CreateBasic(UserName, Password);
            }

            if (!string.IsNullOrEmpty(Method))
            {
                request.Method = Method;
            }

			request.Uri = new Uri(Url);
            
            if (!string.IsNullOrEmpty(ContentType))
            {
            	request.Headers.ContentType = ContentType;
            }

			if (!request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
			{
				request.Content = (string.IsNullOrEmpty(Content)) ? HttpContent.CreateEmpty() : HttpContent.Create(Content);
				request.Headers.ContentLength = request.Content.GetLength();
			}
            
			if (ConnectionTimeout != 0)
			{
				client.TransportSettings.ConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout);
			}

			Project.Log(Level.Info, "Executing HTTP request.");
			Project.Log(Level.Info, "Url: {0}", request.Uri);
			Project.Log(Level.Info, "Method: {0}", request.Method);
			Project.Log(Level.Info, "Content Type: {0}", request.Headers.ContentType);
			Project.Log(Level.Info, "Connection Timeout: {0}", client.TransportSettings.ConnectionTimeout);

            try
            {
                HttpResponseMessage response = client.Send(request);

				if (FailOnError)
				{
					response.EnsureStatusIsSuccessful();	
				}

				if (!string.IsNullOrEmpty(StatusCodeProperty))
				{
					Project.Properties[StatusCodeProperty] = response.StatusCode.ToString();
				}

				if (successCodes.Contains(response.StatusCode) && !string.IsNullOrEmpty(ResponseProperty))
                {
                    Project.Properties[ResponseProperty] = response.Content.ReadAsString();
                }

				Project.Log(Level.Info, "Received HTTP response.");
				Project.Log(Level.Info, "Status Code: {0}", response.StatusCode);
				Project.Log(Level.Info, "Content Type: {0}", response.Headers.ContentType);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                string message = string.Format("The HTTP '{0}' request to '{1}' failed:{2}{3}", Method, Url, Environment.NewLine, ex.Message);
                throw new BuildException(message, ex);
            }
        }
        /// <summary>
        /// Example of calling Actor.svc/participant to get participant details
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SearchResults_SelectedIndexChanged(object sender, EventArgs e)
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
            string clid = null;

            using (HttpClient client = new HttpClient(baseurl))
            {
                RequestHeaders headers = new RequestHeaders();
                headers.Add("enterpriseGuid", enterprise);
                headers.Add("securityToken", Session["SecurityToken"].ToString());

                clid = SearchResults.SelectedValue;

                HttpResponseMessage resp = client.Send(HttpMethod.GET, "Actor.svc/participant/" + clid, headers);
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Participant));
                Participant participant = (Participant)ser.ReadObject(resp.Content.ReadAsStream());

                PartNameLabel.Text = participant.FirstName + " " + participant.LastName;
                PartIdLabel.Text = participant.ID.ToString();
                PartAddrLabel.Text = participant.Address1 + " " + participant.Address2;
                PartGenderLabel.Text = participant.Gender.ToString();
            }

            DisplayAssessments(clid);
        }
        /// <summary>
        /// Example of calling Security.svc/getsiteinfo to log into
        /// a specific site.
        /// </summary>
        private void LogonSite()
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string authtoken = Session["AuthToken"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];

            using (HttpClient client = new HttpClient(baseurl))
            {
                HttpResponseMessage resp = client.Send(HttpMethod.GET, string.Format("Security.svc/SSOSiteLogin/{0}/{1}/{2}/-300", siteid, enterprise, authtoken));
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer siteSer = new DataContractJsonSerializer(typeof(string));
                string SiteLoginResponse = siteSer.ReadObject(resp.Content.ReadAsStream()) as string;
                Session["SecurityToken"] = SiteLoginResponse;
            }
        }
        /// <summary>
        /// Example of calling Security.svc/getsiteinfo to display details
        /// for a specific site.
        /// </summary>
        private void DisplaySiteInfo()
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];
            string securitytoken = Session["SecurityToken"].ToString();
            string authtoken = Session["AuthToken"].ToString();

            using (HttpClient client = new HttpClient(baseurl))
            {
                RequestHeaders headers = new RequestHeaders();
                headers.Add("Content-Type", "application/json");
                headers.Add("enterpriseGuid", enterprise);
                headers.Add("securityToken", securitytoken);

                HttpResponseMessage resp = client.Send(HttpMethod.GET, "Security.svc/GetSiteInfo/" + siteid, headers);
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer siteSer = new DataContractJsonSerializer(typeof(SiteInfo));
                SiteInfo siteInfo = (SiteInfo)siteSer.ReadObject(resp.Content.ReadAsStream());

                SiteNameLabel.Text = siteInfo.SiteName;
                AddressLabel.Text = siteInfo.Address1 + " " + siteInfo.Address2;
                PhoneLabel.Text = siteInfo.PhoneNumber;
                ZipLabel.Text = siteInfo.ZipCode;
                DisabledLabel.Text = siteInfo.Disabled ? "Yes" : "No";
            }
        }
        /// <summary>
        /// Example of calling Form.svc/Forms/Program/GetPrograms to get a 
        /// list of programs for a specific site.
        /// </summary>
        private void DisplayPrograms()
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];

            using (HttpClient client = new HttpClient(baseurl))
            {
                RequestHeaders headers = new RequestHeaders();
                headers.Add("enterpriseGuid", enterprise);
                headers.Add("securityToken", Session["SecurityToken"].ToString());

                HttpResponseMessage resp = client.Send(HttpMethod.GET, "Form.svc/Forms/Program/GetPrograms/" + siteid, headers);
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ProgramInfo[]));
                ProgramInfo[] progInfo = (ProgramInfo[])ser.ReadObject(resp.Content.ReadAsStream());

                foreach (ProgramInfo pinfo in progInfo)
                {
                    ProgramDropList.Items.Add(new ListItem(pinfo.Name, pinfo.ID.ToString()));
                }
            }
        }
        /// <summary>
        /// Example of calling Form.svc/Forms/Assessments/GetAllAssessementResponses
        /// to get a list of assessment responses for a participant.
        /// </summary>
        /// <param name="clid"></param>
        private void DisplayAssessments(string clid)
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];

            using (HttpClient client = new HttpClient(baseurl))
            {
                RequestHeaders headers = new RequestHeaders();
                headers.Add("enterpriseGuid", enterprise);
                headers.Add("securityToken", Session["SecurityToken"].ToString());

                string body = "{\"CLID\":\"";
                body = body + clid + "\",\"surveyResponderType\":";
                body = body + (int)SurveyResponderType.Client + "}";

                HttpResponseMessage resp = client.Send(HttpMethod.POST,
                                                    "Form.svc/Forms/Assessments/GetAllAssessementResponses/",
                                                    headers, HttpContent.Create(body, "application/json; charset=utf-8"));
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AssessmentResponse[]));
                AssessmentResponse[] responses = (AssessmentResponse[])ser.ReadObject(resp.Content.ReadAsStream());

                foreach (AssessmentResponse response in responses)
                {
                    Panel2.Controls.Add(new LinkButton() { Text = response.SurveyName + " " + response.SurveyDate.ToString() + " " +
                        response.SurveyResponseID.ToString() + " " + response.SurveyTaker });
                }
            }
        }
        /// <summary>
        /// Example of calling Search.svc/Search/ to search for participants
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SearchText_TextChanged(object sender, EventArgs e)
        {
            string siteid = Session["SessionID"].ToString();
            string enterprise = Session["EnterpriseGUID"].ToString();
            string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"];

            using (HttpClient client = new HttpClient(baseurl))
            {
                RequestHeaders headers = new RequestHeaders();
                headers.Add("enterpriseGuid", enterprise);
                headers.Add("securityToken", Session["SecurityToken"].ToString());

                string programId = ProgramDropList.SelectedValue;
                string searchtext = SearchText.Text;

                HttpResponseMessage resp = client.Send(HttpMethod.GET, "Search.svc/Search/" + programId + "/" + searchtext, headers);
                resp.EnsureStatusIsSuccessful();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SearchResult[]));
                SearchResult[] results = (SearchResult[])ser.ReadObject(resp.Content.ReadAsStream());

                if (results.Length == 0)
                {
                    SearchResults.Items.Clear();
                }
                else
                {
                    foreach (SearchResult result in results)
                    {
                        SearchResults.Items.Add(new ListItem(result.FName + " " + result.LName, result.CLID.ToString()));
                    }
                }
            }
        }
 static HttpResponseMessage Method(HttpClient client, HttpMethod method, Uri uri)
 {
     CheckNull(client, "client");
     CheckNull(uri, "uri");
     return(client.Send(method, uri));
 }