Example #1
5
        static async Task RunAsync()
        {
            using (var client = new HttpClient()) // met het gebruik van using zorgen we ervoor dat alles netjes wordt opgeruimd als je buiten de scope zit. 
            {
                client.BaseAddress = new Uri("http://localhost:50752/"); //de URL waar onze website op draait
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //we krijgen JSON terug van onze API

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/RekeningsApi/1"); //ik wil de eerste klant ophalen. Deze bevindt zich in de api, de RekeningsApiController en dan nummer 1
                if (response.IsSuccessStatusCode) //Controleren of we geen 404 krijgen, maar iets in de 200-reeks
                {
                    Rekening rekening = await response.Content.ReadAsAsync<Rekening>(); //zetten de response asynchroon om in een rekening-object
                    Console.WriteLine("Rekeningnaam: {0}\tBeschrijving: {1}\tSaldo: {2}", rekening.RekeningNaam, rekening.Beschrijving, rekening.Saldo); //en schrijven deze naar de console
                }
                //Console.ReadKey(); //even op een toets drukken om verder te gaan


                var klantNew = new Klant() { Beschrijving = "willekeurige klant", Name = "John Doe" }; //we maken een nieuwe klant aan en vullen deze meteen met info
                response = await client.PostAsJsonAsync("api/KlantsApi/", klantNew); //we sturen deze nieuwe klant asynchroon naar de api via een HTTP Post

                if (response.IsSuccessStatusCode) //check of we geen 404 of iets dergelijks krijgen
                {
                    //Console.ReadKey();

                }

                // HTTP POST
                //let op: je kan pas een rekening aanmaken als je de klant eerst hebt aangemaakt vanwege je constraints; een rekening die niet bij een klant hoort zou natuurlijk raar zijn.
                
                    var RekeningNew = new Rekening() { Beschrijving = "Nieuw product", RekeningNaam = "zilvervloot-rekening", Saldo = 5000.50, KlantId = 2 };//nieuwe rekening aanmaken

                    response = await client.PostAsJsonAsync("api/RekeningsApi/", RekeningNew);
                    if (response.IsSuccessStatusCode) //check of we geen 404 of iets dergelijks krijgen
                    {
                        Console.WriteLine("klant aangemaakt");

                        /*Console.ReadKey();
                        Uri responseUrl = response.Headers.Location;

                        // HTTP PUT
                        RekeningNew.Saldo = 80;   // Update price
                        response = await client.PutAsJsonAsync(responseUrl, RekeningNew);

                        // HTTP DELETE
                        response = await client.DeleteAsync(responseUrl);*/
                    }
                
            }
        }
Example #2
1
        private static void RunClient()
        {
            // TEST CERTIFICATE ONLY, PLEASE REMOVE WHEN YOU REPLACE THE CERT WITH A REAL CERT
            // Perform the Server Certificate validation
            ServicePointManager.ServerCertificateValidationCallback += Program.RemoteCertificateValidationCallback;

            // set up the client without client certificate
            HttpClient client = new HttpClient();
            client.BaseAddress = _baseAddress;
            
            // set up the client with client certificate
            WebRequestHandler handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual; // this would pick from the Current user store
            handler.ClientCertificates.Add(GetClientCertificate());

            HttpClient clientWithClientCert = new HttpClient(handler);
            clientWithClientCert.BaseAddress = _baseAddress;
            HttpResponseMessage response;

            //// How to post a sample item with success
            SampleItem sampleItem = new SampleItem { Id = 1, StringValue = "hello from a new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting the first item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to post another sample item with success
            sampleItem = new SampleItem { Id = 2, StringValue = "hello from a second new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting a second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the two newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get an sample item with id = 2
            response = client.GetAsync("api/sample/2").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting the second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // Posting without client certificate will fail 
            sampleItem = new SampleItem { Id = 3, StringValue = "hello from a new sample item" };
            response = client.PostAsJsonAsync("api/sample/", sampleItem).Result;
            Console.WriteLine("Posting the third item without client certificate fails:\n" + response.StatusCode + "\n");
            response.Dispose();
        }
        public async Task AddUserAsync(User user)
        {
            var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:1874/", UriKind.RelativeOrAbsolute);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var JsonData = new User
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                Password = user.Password,
                MedicalSpecialites = user.MedicalSpecialites,
                Address = user.Address,
                PhoneNo = user.PhoneNo
            };
            var response = await httpClient.PostAsJsonAsync(new Uri(BaseUrl1), JsonData);


            if (response.IsSuccessStatusCode)
            {
                post = true;

                gizmoUrl = response.Headers.Location.ToString();

                putlink = gizmoUrl;
                id = putlink.Remove(0, 34);
            }
        }
        public static void Main()
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri("http://localhost:7661/")
            };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var album = new Album
            {
                Title = "Runaway",
                Year = 1986,
                Producer = "Bon Jovi"
            };

            HttpResponseMessage response = client.PostAsJsonAsync("api/albums", album).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} added!", album.GetType().Name);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
        public static void AddArtistJson(HttpClient client)
        {
            client.DefaultRequestHeaders.Accept.Add(new
                MediaTypeWithQualityHeaderValue("application/json"));

            Console.WriteLine("Enter artist name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter artist country");
            string country = Console.ReadLine();
            Console.WriteLine("Enter artist birth date");
            DateTime birthDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US"));
            Artist artist = new Artist { Name = name, Country = country, DateOfBirth = birthDate };
            HttpResponseMessage response =
                client.PostAsJsonAsync("api/artists", artist).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Artist added");
            }
            else
            {
                Console.WriteLine("{0} ({1})",
                    (int)response.StatusCode, response.ReasonPhrase);
            }
        }
        private async Task RunAsync()
        {
            var newlog = new IPC.Models.IPCLog();

            newlog.Action = "Check";
            newlog.Error = string.Empty;
            newlog.IPCName = "IPCTest";
            newlog.Time = $"{DateTime.Now.ToShortDateString()}-{DateTime.Now.ToShortTimeString()}";

            string site = @"http://localhost:53226/api";

            string servicesite = string.Format("{0}/{1}/", site, "logging");

            string URI = servicesite;
          

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(servicesite);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                var response = await client.PostAsJsonAsync("api/products", newlog);
                if (response.IsSuccessStatusCode)
                {
                    
                }
            }
        }
 private async void registerSrvData()
 {
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(URL);
     HttpResponseMessage response = await client.PostAsJsonAsync("/rest/add/Service", srv).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
     this.Close();
 }
 /// <summary>
 /// Get the card that the Ai passed in player will play
 /// </summary>
 /// <param name="hand">The current cards that are in play</param>
 /// <param name="player">The player that will be playing the card</param>
 /// <returns>The card played</returns>
 public async System.Threading.Tasks.Task<Card> GetAiCardPlay(Hand hand, Player player)
 {
     if (_feature.FeatureEnabled(AiSimulation.SimService))
     {
         var sim = new BasicTrumpSimluation();
         using (var client = new HttpClient())
         {
             // translate inputs to the sim object
             var response = await client.PostAsJsonAsync("api/api/BasicTrumpSimulation", sim);
             if (response.IsSuccessStatusCode)
             {
                 var card = response.Content.ReadAsAsync<Dto.AiSimulation.Card>();
                 // map to our card
                 throw new NotImplementedException();
             }
             else
             {
                 // errored out yo
                 throw new NotImplementedException();
             }
         }
     }
     else
     {
         var aiSim = new AiSimulation();
         return aiSim.PlayCard(hand, player);
     }
 }
		internal static async Task SendDataToWebhook(Models.BathroomStatusModel bathroomStatus)
		{
			try
			{
				using (var client = new HttpClient())
				{
				
					client.BaseAddress = new Uri("http://nibodev.azurewebsites.net/v1/");
					client.DefaultRequestHeaders.Accept.Clear();
					client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

					HttpResponseMessage response = await client.PostAsJsonAsync("Bathroom/SaveStatus", bathroomStatus);
					response.EnsureSuccessStatusCode();

					if (response.IsSuccessStatusCode)
					{

					}
				}
			}
			catch (Exception ex)
			{
				///TODO
			}
		}
Example #10
1
        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.ReflectedType == null) throw new Exception("Unknown service type");
            var model = new InvocationApiModel
            {
                ServiceName = invocation.Method.ReflectedType.Name,
                MethodName = invocation.Method.Name,
                Parameters = invocation.Arguments
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = client.PostAsJsonAsync("invokeMethod", model)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();

                if (!response.IsSuccessStatusCode) return;

                string result = response.Content.ReadAsStringAsync()
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();
                object returnValue = JsonConvert.DeserializeObject(result, invocation.Method.ReturnType);
                invocation.ReturnValue = returnValue;
            }
        }
Example #11
1
        public async Task UpdateLicenses()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.dropbox.com");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + txtAccesstoken.Text);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.PostAsJsonAsync("/1/team/get_info", new Licenses());
                var content = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    throw new Exception("A 409 error message was returned from Dropbox, this can occur for the following reasons: \n \n 409 No available licenses. \n 409 User is already on the team or has already been invited. \n 409 User is already on another team.");
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    LicensesObj licenses = new JavaScriptSerializer().Deserialize<LicensesObj>(content);
                    lbllicensesavailablenumber.Text = Convert.ToString(licenses.num_licensed_users);
                    lblprovisionedusersnumber.Text = Convert.ToString(licenses.num_provisioned_users);
                }
                else
                {
                    throw new Exception(content.Replace("{", "").Replace("}", "").Replace("\"", " "));
                }
            }
        }
Example #12
0
        /// <summary>
        /// Register plugin. All plugin must be registered first.
        /// </summary>
        private static void RegisterPlugin()
        {
            var job = new PluginJob
            {
                AssemblyPath = PluginAssemblyPath,
                JobName = "MyAssemblyPluginJob",
                JobGroup = "MyJobGroup"
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = client.PostAsJsonAsync("api/plugins/", job).Result;
                string resultStr = response.Content.ReadAsStringAsync().Result;

                dynamic result = JsonConvert.DeserializeObject<dynamic>(resultStr);

                if (result != null)
                {
                    Console.WriteLine(resultStr);
                    _jobId = new Guid(result.id.ToString());
                }
            }
        }
Example #13
0
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://internal-devchallenge-2-dev.apphb.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string guid;
                for (int i = 0; i < 20; i++)
                {
                    guid = Guid.NewGuid().ToString();
                    HttpResponseMessage response = await client.GetAsync("values/" + guid);
                    string result="";
                    if (response.IsSuccessStatusCode)
                    {
                        AAItem item = await response.Content.ReadAsAsync<AAItem>();
                        switch (item.algorithm)
                        {
                            case "IronMan":
                                Algorithms.SortArray(item, false);//check
                                Algorithms.ShiftVowels(item);//check
                                result = Algorithms.AsciiConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "TheIncredibleHulk":
                                Algorithms.ShiftVowels(item);//check
                                Algorithms.SortArray(item, true);//check
                                result = Algorithms.AsterixConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "Thor":
                                //1
                                Algorithms.crazy(item);
                                Algorithms.SortArray(item, false);//check
                                Algorithms.AltCase(item);
                                Algorithms.Fib(item);
                                result = Algorithms.AsterixConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "CaptainAmerica":
                                Algorithms.ShiftVowels(item);//check
                                Algorithms.SortArray(item, true);//check
                                Algorithms.Fib(item);
                                result = Algorithms.AsciiConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                        }

                        Calculation postval = new Calculation();
                        postval.encodedValue = result;
                        response = await client.PostAsJsonAsync(string.Format("values/{0}/{1}", guid, item.algorithm), postval);
                        Console.WriteLine(i);
                        Console.WriteLine(item.algorithm);
                        AAResponse asdf = await response.Content.ReadAsAsync<AAResponse>();
                        Console.WriteLine(asdf.status);
                        Console.WriteLine(asdf.message);
                    }
                }
            }
        }
Example #14
0
 static async Task PostGreetingJson(string greeting)
 {
     var client = new HttpClient();
     HttpResponseMessage response = await client.PostAsJsonAsync
         (_greetingsBaseUri, greeting);
     response.EnsureSuccessStatusCode();
 }
        public async Task <IActionResult> Index()
        {
            var baseAddress = new System.Uri("https://api.sandbox.faraboom.co/v1/");
            var client      = new System.Net.Http.HttpClient {
                BaseAddress = baseAddress
            };

            client.DefaultRequestHeaders.AcceptLanguage.Clear();
            client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fa"));
            client.DefaultRequestHeaders.Add("App-Key", "13457");
            client.DefaultRequestHeaders.Add("Device-Id", "Your Device Id");
            client.DefaultRequestHeaders.Add("CLIENT-DEVICE-ID", "127.0.0.1");
            client.DefaultRequestHeaders.Add("CLIENT-IP-ADDRESS", "127.0.0.1");
            client.DefaultRequestHeaders.Add("CLIENT-USER-AGENT", "User Agent");
            client.DefaultRequestHeaders.Add("CLIENT-USER-ID", "09120000000");
            client.DefaultRequestHeaders.Add("CLIENT-PLATFORM-TYPE", "WEB");

            var data = new {
                username = "******",
                password = "******",
            };
            var response = await client.PostAsJsonAsync("auth/market/login", data);

            ViewBag.result = await response.Content.ReadAsStringAsync();

            return(View());
        }
Example #16
0
        static void Main(string[] args)
        {
            var address = "http://localhost:900";
            var config = new HttpSelfHostConfiguration(address);
            config.MapHttpAttributeRoutes();

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server running at {0}. Press any key to exit", address);

                var client = new HttpClient() {BaseAddress = new Uri(address)};

                var persons = client.GetAsync("person").Result;
                Console.WriteLine(persons.Content.ReadAsStringAsync().Result);

                var newPerson = new Person {Id = 3, Name = "Luiz"};
                var response = client.PostAsJsonAsync("person", newPerson).Result;

                if (response.IsSuccessStatusCode)
                {
                    var person3 = client.GetAsync("person/3").Result;
                    Console.WriteLine(person3.Content.ReadAsStringAsync().Result);
                }

                Console.ReadLine();
            }

        }
        public void LogInTest()
        {
            var site = ConfigurationManager.AppSettings["site"];

            using (var client = new HttpClient())
            {
                var mock = new
                {
                    first_name = "Test",
                    last_name = "Test",
                    gender = "male",
                    email = "*****@*****.**",
                    access_token = "qfqsdàdddàq,kd!çààè33DFDSNSHSKLZIJ766633SS",
                    id = "49485950595555",
                    timeZone = 2,
                    locale = "fr_FR",
                };

                var task = client.PostAsJsonAsync(site + "/api/users/login", mock);

                task.Wait();

                var result = task.Result;

                result.EnsureSuccessStatusCode();
            }
        }
Example #18
0
        public async Task <ActionResult> Register(UserModel model)
        {
            if (ModelState.IsValid)
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:58376/api/");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //HTTP POST
                    var postTask = client.PostAsJsonAsync <UserModel>("Account", model);
                    postTask.Wait();

                    var result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        UserModel responseMmodel = postTask.Result.Content.ReadAsAsync <UserModel>().Result;

                        if (responseMmodel != null)
                        {
                            model = responseMmodel;
                        }

                        return(View("Index", model));
                    }
                    else
                    {
                        ModelState.AddModelError("", string.Format("{0} - Could not create user record", result.ReasonPhrase));
                    }
                }
            }

            return(View("Index", model));
        }
Example #19
0
        public override void Write(string message, RoggleLogLevel level)
        {
            var newEvent = new OverseerEvent()
            {
                Description = message,
                Name = Source,
                UserId = Key,
                Level =
                    level == RoggleLogLevel.Critical ? OverseerEventLevel.Critical :
                    level == RoggleLogLevel.Debug ? OverseerEventLevel.Debug :
                    level == RoggleLogLevel.Error ? OverseerEventLevel.Error :
                    level == RoggleLogLevel.Info ? OverseerEventLevel.Information :
                    level == RoggleLogLevel.Warning ? OverseerEventLevel.Warning :
                    OverseerEventLevel.Debug
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = AsyncHelper.RunSync(() => client.PostAsJsonAsync("api/events", newEvent));
                if (!response.IsSuccessStatusCode)
                {
                    throw new RoggleException($"Overseer return an error '{response.StatusCode}: {response.ReasonPhrase}'.");
                }
            }
        }
Example #20
0
        static async Task registrarAvanceTipoRegistroUno()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://52.26.20.117/servicio/TramiteDocumentario/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                var Avance = new AvanceDto() { TipoRegistro = "1", 
                                                              FechaAvance = "14/11/2015", 
                                                              Observaciones ="Tramite",
                                                              IdTipoTramiteEstado = "1",
                                                              IdTramite = "1"
                                                              };

                HttpResponseMessage response = await client.PostAsJsonAsync("Tramite.svc/avance", Avance);

                if (response.IsSuccessStatusCode)
                {
                    AvanceResponse _ResponseMessage = await response.Content.ReadAsAsync<AvanceResponse>();
                    Console.WriteLine("ResponseMessage TipoRegistro 1 : " + _ResponseMessage._HeadMessage.ResponseCode);

                }
            }
        }
        // add a stock listing
        static async Task AddAsync(string cnumber, int rlevel)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://x00077517.cloudapp.net/");                             // base URL for API Controller i.e. RESTFul service

                    // add an Accept header for JSON - preference for response 
                    client.DefaultRequestHeaders.
                        Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // POST /api/CreditCard with a listing serialised in request body
                    // create a new credit card
                    CreditCardItem newCard = new CreditCardItem { Number = cnumber, RiskLevel = rlevel };
                    HttpResponseMessage response = await client.PostAsJsonAsync("api/CreditCard", newCard);   // or PostAsXmlAsync
                    if (response.IsSuccessStatusCode)                                                       // 200 .. 299
                    {
                        Uri newCardUri = response.Headers.Location;
                        var card = await response.Content.ReadAsAsync<CreditCardItem>();
                    }
                    else
                    {
                        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #22
0
        public static async Task<bool> SubmitComment(string issueNumber, string commentString)
        {
            // https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-add-comment
            // https://grantadesign.atlassian.net/rest/api/latest/project/10000
            // https://grantadesign.atlassian.net/rest/api/latest/issue/MI-9111/editmeta/

            var credentials = new NetworkCredential(Constants.UserName, Constants.Password);
            var handler = new HttpClientHandler {Credentials = credentials, PreAuthenticate = true};
            using (var client = new HttpClient(handler))
            {
                var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Constants.UserName, Constants.Password))));
                client.DefaultRequestHeaders.Authorization = authHeader;
                client.BaseAddress = new Uri("https://grantadesign.atlassian.net/rest/api/latest/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var jiraComment = new JiraComment { Body = commentString };
                var response = await client.PostAsJsonAsync("issue/" + issueNumber + "/comment", jiraComment);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                return false;
            }
        }
Example #23
0
        public async Task alarm()
        {

            using (var client2 = new HttpClient())
            {
 
                string token=careDeviceId;
                client2.BaseAddress = new Uri("https://api.pushbots.com/push/one");
                client2.DefaultRequestHeaders.Accept.Clear();
                client2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client2.DefaultRequestHeaders.Add("x-pushbots-appid", "55eb927f177959b3338b4567");
                client2.DefaultRequestHeaders.Add("x-pushbots-secret", "50dd3c9198d1766e74a5964db3613e10");
                PushbotsOne onePush = new PushbotsOne();
                onePush.platform = 1;
                // onePush.schedule = "2015-09-08T01:20:00";
                onePush.token = token;
                onePush.msg = patientName + "is now out of fence ";
                Console.WriteLine("before repsonse");
                HttpResponseMessage response = await client2.PostAsJsonAsync("", onePush);
                Console.WriteLine("after response");
                apiResult = "post response";
                if (response.IsSuccessStatusCode)
                {
                    apiResult = "in OK";
                    //Uri patientURL = response.Headers.Location;
                }
                else
                {
                    apiResult = "in ERROR " + await response.Content.ReadAsStringAsync();
                }
            }

        }
Example #24
0
        public void realProcessPaymentHelp(bankEntity bankEntity, int processTime = 2000, string result = "ok")
        {
            Thread.Sleep(processTime);
            var res = new inTimeEntity { PaymentResult = result, BankEnt = new bankEntity { PayId = bankEntity.PayId } };
            var t = Task.Factory.StartNew(() =>
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://win8dev");
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    var resp = client.PostAsJsonAsync("inTimePayment/api/paySOA/paymentResultHookHelp", res).Result;
                    var resContent = resp.Content.ReadAsAsync<string>();
                    //using (var req = new BankServiceClient())
                    //{
                    //    req.processPaymentHelp(be);
                    //}
                    ////using (var req = new PaymentServiceClient())
                    //{
                    //    req.paymentResultHookHelp(res);
                    //}
                }
            });

            t.Wait(100);

            //Thread.Sleep(3000);
            //    var res = new inTimeEntity();
            //    res.PaymentResult = "ok";
        }
Example #25
0
        /// <summary>
        /// Creates the snapshot
        /// </summary>
        /// <param name="url">The url to crawl</param>
        /// <returns>true if the snapshot was successfully created</returns>
        public async Task<string> Get(string url, string userAgent)
        {
            HttpClient client = new HttpClient();
            
            CrawlerConfig config = new CrawlerConfig() 
            {
                ApiId = ConfigurationManager.AppSettings["CrawlerServiceApiId"],
                Application = ConfigurationManager.AppSettings["CrawlerServiceApplication"],
                ExpirationDate = DateTime.UtcNow.AddDays(3),
                Store = true,
                Url = url,
                UserAgent = userAgent
            };

            var response = await client.PostAsJsonAsync<CrawlerConfig>(ConfigurationManager.AppSettings["CrawlerServiceEndPoint"], config);

            response.EnsureSuccessStatusCode();

            var result = response.Content.ReadAsStringAsync().Result;

            if (DurandalViewNotFound(result))
            {
                throw new HttpException(404, "Durandal view not found");
            }

            return result;
        }
        protected async Task<Action> CreateTestAction(string verb = "Created for test goal and activity")
        {
            var session = await Login();

            using (var client = new HttpClient { BaseAddress = new Uri(ServerUrl) })
            {
                client.AcceptJson().AddSessionHeader(session.Id.ToString());
                var action = new Action
                {
                    Verb = verb,
                    Goal =
                        new Goal
                        {
                            Concern = new ConcernMatrix { Coordinates = new Matrix { X = 1, Y = 1 }, Category = 0 },
                            RewardResource =
                                new RewardResourceMatrix { Coordinates = new Matrix { X = 2, Y = 2 }, Category = 0 },
                            Feedback = new GoalFeedback { Threshold = 0, Target = 0, Direction = 0 },
                            Description = "Created for test cases"
                        },
                    Activity = new Activity { Name = "Testing" }
                };
                var actionResponse = await client.PostAsJsonAsync("/api/actions", action);
                Assert.Equal(HttpStatusCode.Created, actionResponse.StatusCode);

                var created = await actionResponse.Content.ReadAsJsonAsync<Action>();

                return created;
            }
        }
        public async Task InvokeRequestResponseService(object scoreRequest, string baseUrl, string key)
        {
            using (var client = new HttpClient())
            {                                
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);

                client.BaseAddress = new Uri(baseUrl);


                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseContent);
                }
            }
        }
Example #28
0
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://hps-dev-prescreen.azurewebsites.net/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var applicant = new Applicant { FullName = "Justin Patterson", Email = "*****@*****.**", PhoneNumber = "817.307.6341" };
                client.DefaultRequestHeaders.Add("X-HPS", "apply");
                client.PostAsJsonAsync("api/v1/applicants", applicant).Wait();
            }

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://hps-dev-prescreen.azurewebsites.net/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Add("X-HPS", "apply");
                var result = client.GetStringAsync(@"api/v1/applicants/[email protected]").Result;

                Console.WriteLine(result);
            }
        }
Example #29
0
 public void Persist(TrackerData trackerData)
 {
     // setup the client
     // -   with a custome handler to approve all server certificates
     var handler = new WebRequestHandler
     {
         ServerCertificateValidationCallback =
             (sender, certificate, chain, errors) => true
     };
     try
     {
         using (var client = new HttpClient(handler))
         {
             // post it
             HttpResponseMessage httpResponseMessage = client.PostAsJsonAsync(_serviceUrl, trackerData).Result;
             if (!httpResponseMessage.IsSuccessStatusCode)
             {
                 Configurator.Configuration.Logger.Warn(string.Format("Data not persisted with status {0}",
                     httpResponseMessage.StatusCode));
             }
         }
     }
     catch (Exception ex)
     {
         Configurator.Configuration.Logger.Error(ex.Message, ex);
     }
 }
Example #30
0
        /// <summary>
        /// Envía una petición a la url especificada con las opciones
        /// de configuración requerida
        /// </summary>
        /// <typeparam name="T">Tipo de dato a esperado</typeparam>
        /// <param name="Url">Url destino</param>
        /// <param name="Method">Tipo de método de la petición</param>
        /// <param name="Data">Objeto a enviar en la petición</param>
        /// <param name="TimeOut">Tiempo de espera en minutos</param>
        /// <returns></returns>
        public static T Request <T>(string Url, HttpMethodEnum Method, object Data = null, string Token = null, int TimeOut = 10)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                try
                {
                    client.Timeout = TimeSpan.FromMinutes(TimeOut);
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("text/plain"));
                    if (!string.IsNullOrEmpty(Token))
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                    }
                    HttpResponseMessage response = null;

                    switch (Method)
                    {
                    case HttpMethodEnum.Get:
                        response = client.GetAsync(Url).Result;
                        break;

                    case HttpMethodEnum.PostJson:
                        response = client.PostAsJsonAsync(Url, Data).Result;
                        break;

                    case HttpMethodEnum.PutJson:
                        response = client.PutAsJsonAsync(Url, Data).Result;
                        break;

                    case HttpMethodEnum.Delete:
                        response = client.DeleteAsync(Url).Result;
                        break;

                    default:
                        break;
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        T result = response.Content.ReadAsAsync <T>().Result;
                        return(result);
                    }
                    else
                    {
                        return(default(T));
                    }
                }
                catch (Exception ex)
                {
                    // Excepciones
                    throw ex;
                }
            }
        }
        public ActionResult Create([Bind(Include = "bill_id,total_price,state,payment_type,date_of_bill,command_reference")] bill bill, long?command_reference)
        {
            httpClient.BaseAddress = new Uri("http://localhost:8081/ConsomiTounsi/");
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            var postTask = httpClient.PostAsJsonAsync <bill>("addBill/" + command_reference, bill);

            postTask.Wait();

            var result = postTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(RedirectToAction("Index"));
            }
            return(View(new bill()));
        }
Example #32
0
        public static async System.Threading.Tasks.Task <Usuario> Registrar(System.Net.Http.HttpClient api, Usuario usuario)
        {
            api.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            Usuario result = null;

            System.Net.Http.HttpResponseMessage response = await api.PostAsJsonAsync("http://aquariovirtual-aquariovirtualapi.azurewebsites.net/RegistrarUsuario", usuario).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsAsync <Usuario>();
            }

            return(result);
        }
Example #33
0
        public static async System.Threading.Tasks.Task <Artigo> Save(System.Net.Http.HttpClient api, Artigo artigo)
        {
            var r = System.Web.HttpContext.Current.Request;
            var f = r.Files;

            api.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            Artigo result = null;

            System.Net.Http.HttpResponseMessage response = await api.PostAsJsonAsync("http://aquariovirtual-aquariovirtualapi.azurewebsites.net/CadastrarArtigo", artigo).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsAsync <Artigo>();
            }

            return(result);
        }
Example #34
0
        public ActionResult Create([Bind(Include = "id,adresse,date,frais,poids,state,deliver_men_id")] delivery delivery, int?idDeliveryMen)
        {
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var postTask = httpClient.PostAsJsonAsync <delivery>(baseAddress + "ConsomiTounsi/Delivery/newDelivery?id=" + delivery.deliver_men_id, delivery);

            postTask.Wait();

            var result = postTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(RedirectToAction("Index"));
            }
            return(View(new delivery()));
        }
Example #35
0
        public ActionResult Create([Bind(Include = "id,dateLimit,decision,objet,state,typeReclamation,users_id")] reclamation reclamation)
        {
            reclamation.state = true;
            if (ModelState.IsValid)
            {
                httpClient.BaseAddress = new Uri("http://localhost:8082/");
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var postTask = httpClient.PostAsJsonAsync <reclamation>("ConsomiTounsi/Reclamation/newReclamation?id=" + 2, reclamation);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }

            return(View(new reclamation()));
        }
Example #36
-1
        static void Main()
        {
            var address = "http://localhost:920/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var team = new Team {Id = 3, Name = "Los Angeles Kings"};
                var team2 = new Team { Name = "Boston Bruins" };
                var player = new Player {Name = "Tyler Bozak", Team = 1};

                Send(HttpMethod.Get, client, address + "api/teams");
                Send(HttpMethod.Get, client, address + "api/teams/1");
                Send(HttpMethod.Get, client, address + "api/teams/1/players");

                Console.WriteLine(client.PostAsJsonAsync(address+"api/teams", team).Result.StatusCode);
                Console.WriteLine();

                Console.WriteLine(client.PostAsJsonAsync(address+"api/teams/1/players", player).Result.StatusCode);
                Console.WriteLine();

                Console.WriteLine(client.PutAsJsonAsync(address + "api/teams/2", team2).Result.StatusCode);
                Console.WriteLine();

                Send(HttpMethod.Get, client, address + "api/teams");
                Send(HttpMethod.Get, client, address + "api/teams/1/players");
            }

            Console.ReadLine();
        }
Example #37
-1
        public static void AddSong(HttpClient client, Song song)
        {
            HttpResponseMessage response = null;

            if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/xml")))
            {
                response = client.PostAsXmlAsync<Song>("api/Song", song).Result;
            }
            else if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")))
            {
                response = client.PostAsJsonAsync<Song>("api/Song", song).Result;
            }

            if (response == null)
            {
                throw new InvalidOperationException("Client must use json or xml.");
            }

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Song added.");
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
Example #38
-1
        private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(products);

            //添加新的联系人
            Product product = new Product { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" };
            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products", product);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products/001");
            product = (await response.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.Name = "赵六";
            product.EmailAddress = "*****@*****.**";
            await httpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products/001", product);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/tyz/api/products/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);
        }