public void Add(Nut nut) { Nut response = null; string uri = string.Format("{0}/{1}/{2}", Address.AbsoluteUri.ToLower(), Account.ToLower(), nut.Table.ToLower()); var client = new HttpClient(uri); MemoryStream ms = new MemoryStream(); DataContractSerializer s = new DataContractSerializer(typeof(Nut)); s.WriteObject(ms, nut); ms.Position = 0; HttpResponseMessage r = client.Post(uri, HttpContent.Create(ms.ToArray(), "application/xml")); ms.Close(); r.EnsureStatusIsSuccessful(); if (r.StatusCode == System.Net.HttpStatusCode.OK) { nut.Uri = uri; } }
/// <summary> /// Example of calling the Security.svc/login method to log into ETO. /// </summary> /// <param name="siteId"></param> protected void Logon(string siteId) { string userName = Session["Username"].ToString(); string password = Session["Password"].ToString(); string enterprise = Session["EnterpriseGUID"].ToString(); string baseurl = WebConfigurationManager.AppSettings["ETOSoftwareWS_BaseUrl"]; try { HttpClient client = new HttpClient(baseurl); //below is incorrect string json = string.Format("{{\"security\":{{\"Email\":\"{0}\",\"Password\":\"{1}\"}}}}", userName, password); HttpContent content = HttpContent.Create(json,"application/json"); HttpResponseMessage resp = client.Post("Security.svc/SSOAuthenticate/", content); resp.EnsureStatusIsSuccessful(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SSOAuthenticateResponseObject)); SSOAuthenticateResponseObject SSOAuthenticationResponse = serializer.ReadObject(resp.Content.ReadAsStream()) as SSOAuthenticateResponseObject; Session["AuthToken"] = SSOAuthenticationResponse.SSOAuthenticateResult.SSOAuthToken; } catch (Exception ex) { Response.Redirect("Default.aspx"); } }
public void EnviaXml() { XmlReader respostaXml; try { //string link = "http://homologacaows.tecgraf.puc-rio.br:8090/comm/"; //HTTP://homologacaows.tecgraf.puc-rio.br:8090/comm/sinal string link = "http://br.tecgraf.puc-rio.br:8085/comm/"; if (listaPosicoes.Count > 0) { StringBuilder documentoXml = GeraXml.getXml(listaPosicoes); if (documentoXml != null) { #region Envia xml try { HttpClient clienteHttp = new HttpClient(link); HttpResponseMessage response = null; response = clienteHttp.Post(string.Format("sinal?xml={0}", Uri.EscapeUriString(documentoXml.ToString())), HttpContent.CreateEmpty()); response.EnsureStatusIsSuccessful(); respostaXml = response.Content.ReadAsXmlReader(); } catch (Exception ex) { throw new Exception("Não foi possível enviar o xml. Erro: " + ex.Message); } #endregion Resposta(respostaXml); } } else { teveErro = false; } } catch (Exception ex) { throw new Exception(ex.Message); } }
public IEnumerable<Package> GetUnfinishedPackages(IEnumerable<string> packageIDs, Guid accessKey) { using (var client = new HttpClient(_serviceRoot.Value)) { string uri = string.Format("{0}/{1}", ServiceConstants.PackageServiceName, accessKey); HttpContent content = HttpContentExtensions.CreateDataContract(packageIDs); using (HttpResponseMessage response = client.Post(uri, content)) { if (response.StatusCode != HttpStatusCode.OK) { _orchardServices.Notifier.Error(T(response.ReadContentAsStringWithoutQuotes())); return new List<Package>(); } return response.Content.ReadAsDataContract<IEnumerable<Package>>(); } } }
static void InsertLocation(HttpClient client, Location location) { Console.WriteLine("Inserting location"); Console.WriteLine(); string insertUri = "Locations"; HttpContent content = HttpContentExtensions.CreateJsonDataContract(location); using (HttpResponseMessage response = client.Post(insertUri, content)) { response.EnsureStatusIsSuccessful(); } }
// public List<List> GetAllLists() // { // // } public List CreateList(List list) { var serializer = new XmlSerializer(typeof(List), "http://schemas.listicus.com"); HttpClient client = new HttpClient(); string listXml = XmlSerializerHelper.SerializeToString(serializer, list); HttpResponseMessage returnValue = client.Post(ListicusRestUrl, "text/xml", HttpContent.Create(listXml)); if (returnValue.StatusCode == HttpStatusCode.OK) { List returnedOrder = XmlSerializerHelper.DeserializeString<List>(serializer, returnValue.Content.ReadAsString()); return returnedOrder; } else { throw new HttpResponseError(returnValue.StatusCode, returnValue.Content.ReadAsString()); } }
public void CreateScreenshot(string packageId, string packageVersion, string externalScreenshotUrl) { var screenshot = new Screenshot { ScreenshotUri = externalScreenshotUrl, PackageId = packageId, PackageVersion = packageVersion }; string serviceRoot = _orchardServices.WorkContext.CurrentSite.As<GallerySettingsPart>().ServiceRoot; string accessKey = _userkeyService.GetAccessKeyForUser(_authenticationService.GetAuthenticatedUser().Id).AccessKey.ToString(); string uri = string.Format("{0}/{1}", ServiceConstants.ScreenshotServiceName, accessKey); using (var client = new HttpClient(serviceRoot)) { HttpContent screenshotContent = HttpContentExtensions.CreateDataContract(screenshot); using (HttpResponseMessage response = client.Post(uri, screenshotContent)) { if (response.StatusCode != HttpStatusCode.OK) { _orchardServices.Notifier.Error(T("Could not create screenshot. {0}", response.ReadContentAsStringWithoutQuotes())); } } } }
public static string CreateHostedZone(string domainName, string callerReference, string comment) { var httpClient = new HttpClient(); var route53Uri = new Uri(Route53Messages.CreateHostedZoneUri); // Create Request Messages var route53RequestMessage = Route53Messages.CreateHostedZoneRequestMessage(domainName, callerReference, comment); Console.WriteLine(route53RequestMessage); var route53Request = HttpContent.Create(route53RequestMessage); // Add Authorization Headers to request var amazonAuthHeader = string.Format("AWS3-HTTPS AWSAccessKeyId={0},Algorithm=HmacSHA1,Signature={1}", Authentication.AwsAccessKeyId, Authentication.AwsAuthSignature); httpClient.DefaultHeaders.Add("X-Amzn-Authorization", amazonAuthHeader); httpClient.DefaultHeaders.Add("x-amz-date", Authentication.DateTimeRfc822); // Make CreateHostedZone request var output = httpClient.Post(route53Uri, route53Request); return output.Content.ReadAsString(); }
private HttpResponseMessage WebRequest(string method, string url, string postData) { System.Net.ServicePointManager.Expect100Continue = false; using (HttpClient client = new HttpClient()) { if (string.Equals(method, "POST")) { using (var body = HttpContent.Create(postData, "application/x-www-form-urlencoded")) { return client.Post(url, body).EnsureStatusIsSuccessful(); } } else { return client.Get(url).EnsureStatusIsSuccessful(); } } }
public PhotoUpload UploadPhoto(string token, byte[] image, string name, string contentType, string caption) { var uploadPhotoUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/me/photos", UrlResources.GraphApiUrl)); var parameters = new ContentBuilder(); parameters.AddParameter("access_token", token); parameters.AddParameter("message", caption); using (HttpClient client = new HttpClient()) { using (var body = parameters.BuildMultiPartContent(image, name, contentType)) { using (var response = client.Post(uploadPhotoUrl, body).EnsureStatusIsSuccessful()) { return response.Content.ReadAsJsonDataContract<PhotoUpload>(); } } } }
public void SetStatus(string token, string status) { var userStatusSetUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/me/feed", UrlResources.GraphApiUrl)); var parameters = new ContentBuilder(); parameters.AddParameter("access_token", token); parameters.AddParameter("message", status); using (HttpClient client = new HttpClient()) { using (var response = client.Post(userStatusSetUrl, parameters.BuildFormContent()).EnsureStatusIsSuccessful()) { } } }
public static bool getBetafaceResults(Face face) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // connect to webservice Console.Out.WriteLine("Connecting to webservice..."); HttpClient client = new HttpClient(ServiceUri); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // upload images Console.Out.WriteLine("Uploading images..."); String guid = null; //Dictionary<Guid, string> images = new Dictionary<Guid, string>(); if (!String.IsNullOrEmpty(face.Path) && File.Exists(face.Path)) { byte[] data = ReadFile(face.Path); if (null != data) { Console.Out.WriteLine("transfer file " + face.Path); //transfer file ImageRequestBinary request = new ImageRequestBinary(); request.api_key = Username; request.api_secret = Password; request.detection_flags = "23"; //binary representing flags detection|recognition|bestface|classifiers request.imagefile_data = Convert.ToBase64String(data); request.original_filename = face.Path; HttpContent body = HttpContentExtensions.CreateXmlSerializable(request); System.Net.ServicePointManager.Expect100Continue = false; using (HttpResponseMessage response = client.Post("UploadNewImage_File", body)) { // Throws an exception if not OK response.EnsureStatusIsSuccessful(); BetafaceImageResponse ret = response.Content.ReadAsXmlSerializable<BetafaceImageResponse>(); if (ret.int_response == 0) { face.BetafaceId = ret.img_uid; // add betafaceid to face guid = ret.img_uid; Console.Out.WriteLine("transfer ok"); } else { Console.Out.WriteLine("error " + ret.int_response + " " + ret.string_response); return false; } } } } else { Console.Out.WriteLine("File not found " + face.Path); // if filepath invalid, return true bc don't want to keep in queue return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // retreive results Console.Out.WriteLine("Waiting for results..."); ImageInfoRequestUid req = new ImageInfoRequestUid(); req.api_key = Username; req.api_secret = Password; req.img_uid = guid; HttpContent bod = HttpContentExtensions.CreateXmlSerializable(req); System.Net.ServicePointManager.Expect100Continue = false; using (HttpResponseMessage response = client.Post("GetImageInfo", bod)) { // Throws an exception if not OK response.EnsureStatusIsSuccessful(); response.Content.LoadIntoBuffer(); string str = response.Content.ReadAsString(); BetafaceImageInfoResponse ret = response.Content.ReadAsXmlSerializable<BetafaceImageInfoResponse>(); if (ret.int_response == 0) { string xmlFilepath = "..\\..\\Images\\BetafaceResults\\" + guid + ".xml"; Console.Out.WriteLine("writing result to " + xmlFilepath); using (StreamWriter sw = new StreamWriter(xmlFilepath)) { sw.WriteLine(str); } updateFacesFromXML(face, xmlFilepath); return true; } else { Console.Out.WriteLine("error " + ret.int_response + " " + ret.string_response); return false; } } }
//initiate the request to modify the call to be sent to twilio server with appropriate callback url private static void InitiateCallModify(Entity.CallBase call, string redirectUrl) { if (call == null || string.IsNullOrEmpty(call.CallTwilioId) || string.IsNullOrEmpty(redirectUrl)) { return; } TwilioSettings twilioSettings = new TwilioSettings(); redirectUrl = string.Format("{0}{1}", twilioSettings.TwilioTwiMLCallbackUrl, redirectUrl); var postUrl = string.Format("{0}/Accounts/{1}/Calls/{2}", twilioSettings.TwilioApiVersion, twilioSettings.TwilioAccountSid, call.CallTwilioId); if (log.IsDebugEnabled) { log.Debug("InitiateCallModify.postUrl." + postUrl); } using (HttpClient httpClient = new HttpClient("https://api.twilio.com/")) { HttpUrlEncodedForm frm = new HttpUrlEncodedForm(); //add the form fields that twilio expects frm.Add("Method", "POST"); frm.Add("Url", redirectUrl); //set the security credentials for the http post httpClient.TransportSettings.Credentials = new NetworkCredential(twilioSettings.TwilioAccountSid, twilioSettings.TwilioAuthToken); //send request to twilio using (HttpResponseMessage httpResp = httpClient.Post(postUrl, frm.CreateHttpContent())) { //don't need to do anything with the response of the http post //twilio sends the response in a seperate http request to the callback url } } }
protected static void Establish_context() { client = new HttpClient(); entity = Script.PersonData.CreateBasicEntityWithOneMapping(); var getResponse = client.Get(ServiceUrl["Person"] + entity.Id); person = getResponse.Content.ReadAsDataContract<EnergyTrading.MDM.Contracts.Sample.Person>(); mappingId = person.Identifiers.Where(x => !x.IsMdmId).First(); var mappingGetResponse = client.Get(ServiceUrl["Person"] + person.NexusId() + "/mapping/" + mappingId.MappingId); var mapping_etag = mappingGetResponse.Headers.ETag; var mappingFromService = mappingGetResponse.Content.ReadAsDataContract<MappingResponse>(); MdmId postMapping = mappingFromService.Mappings[0]; newEndDate = mappingFromService.Mappings[0].EndDate.Value.AddDays(1); postMapping.EndDate = newEndDate; var content = HttpContentExtensions.CreateDataContract(postMapping); client.DefaultHeaders.Add("If-Match", mapping_etag != null ? mapping_etag.Tag : string.Empty); mappingUpdateResponse = client.Post(ServiceUrl["Person"] + string.Format("{0}/Mapping/{1}", entity.Id, mappingFromService.Mappings[0].MappingId), content); }
public bool authorize(String authCode) { // get the access token HttpClient http = new HttpClient(baseUri); HttpUrlEncodedForm req = new HttpUrlEncodedForm(); req.Add("code", authCode); req.Add("client_secret", client_secret); req.Add("client_id", client_id); HttpResponseMessage resp = http.Post("access_token", req.CreateHttpContent()); if (resp.StatusCode == System.Net.HttpStatusCode.OK) { token = resp.Content.ReadAsJsonDataContract<AccessToken>(); auth = true; return true; } auth = false; return false; }