static void PlatformOpen(string number) { ValidateOpen(number); var phoneNumber = string.Empty; #if __ANDROID_24__ if (Platform.HasApiLevelN) { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.GetDefault(Java.Util.Locale.Category.Format).Country); } else if (Platform.HasApiLevel(BuildVersionCodes.Lollipop)) #else if (Platform.HasApiLevel(BuildVersionCodes.Lollipop)) #endif { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.Default.Country); } else #pragma warning disable CS0618 { phoneNumber = PhoneNumberUtils.FormatNumber(number); } #pragma warning restore CS0618 phoneNumber = URLEncoder.Encode(phoneNumber, "UTF-8"); var dialIntent = ResolveDialIntent(phoneNumber) .SetFlags(ActivityFlags.ClearTop) .SetFlags(ActivityFlags.NewTask); Platform.AppContext.StartActivity(dialIntent); }
static void PlatformOpen(string number) { ValidateOpen(number); var phoneNumber = string.Empty; if (Platform.HasApiLevelN) { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.GetDefault(Java.Util.Locale.Category.Format).Country) ?? phoneNumber; } else { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.Default.Country) ?? phoneNumber; } // if we are an extension then we need to encode if (phoneNumber.Contains(',') || phoneNumber.Contains(';')) { phoneNumber = URLEncoder.Encode(phoneNumber, "UTF-8") ?? phoneNumber; } var dialIntent = ResolveDialIntent(phoneNumber); var flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; if (Platform.HasApiLevelN) { flags |= ActivityFlags.LaunchAdjacent; } dialIntent.SetFlags(flags); Platform.AppContext.StartActivity(dialIntent); }
private static string getData() { StringBuffer response = null; URL obj = new URL("http://192.168.1.17/easyserver/WebService.php"); switch (mFunction) { case "setUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8") + "&name=" + URLEncoder.Encode(mName, "UTF-8") + "&age=" + URLEncoder.Encode(mAge, "UTF-8"); break; case "getUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8"); break; } //creación del objeto de conexión HttpURLConnection con = (HttpURLConnection)obj.OpenConnection(); //Agregando la cabecera //Enviamos la petición por post con.RequestMethod = "POST"; con.DoOutput = true; con.DoInput = true; con.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Envio de datos //obtener el tamaño de los datos con.SetFixedLengthStreamingMode(data.Length); /* * OutputStream clase abstracta que es la superclase de todas las clases que * representan la salida de un flujo de bytes. Un flujo de salida acepta bytes de salida. * BufferOutputStream es la clase que implementa un flujo de salida con buffer */ OutputStream ouT = new BufferedOutputStream(con.OutputStream); byte[] array = Encoding.ASCII.GetBytes(data); ouT.Write(array); ouT.Flush(); ouT.Close(); /* * Obteniendo datos * BufferedRead Lee texto de una corriente de caracteres de entrada, * Un InputStreamReader es un puente de flujos de streams de caracteres: se lee los * bytes y los decodifica en caracteres */ BufferedReader iN = new BufferedReader(new InputStreamReader(con.InputStream)); string inputLine; response = new StringBuffer(); while ((inputLine = iN.ReadLine()) != null) { response.Append(inputLine); } iN.Close(); return(response.ToString()); }
public virtual void TestChangeTrackerWithDocsIds() { Uri testURL = GetReplicationURL(); ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, null); IList <string> docIds = new AList <string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTrackerDocIds.SetDocIDs(docIds); string docIdsUnencoded = "[\"doc1\",\"doc2\"]"; string docIdsEncoded = URLEncoder.Encode(docIdsUnencoded); string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s" , docIdsEncoded); string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath(); NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath); changeTrackerDocIds.SetUsePOST(true); IDictionary <string, object> postBodyMap = changeTrackerDocIds.ChangesFeedPOSTBodyMap (); NUnit.Framework.Assert.AreEqual("_doc_ids", postBodyMap.Get("filter")); NUnit.Framework.Assert.AreEqual(docIds, postBodyMap.Get("doc_ids")); string postBody = changeTrackerDocIds.ChangesFeedPOSTBody(); NUnit.Framework.Assert.IsTrue(postBody.Contains(docIdsUnencoded)); }
/// <summary> /// Helper function to encode the URL of the filename of the job-history /// log file. /// </summary> /// <param name="logFileName">file name of the job-history file</param> /// <returns>URL encoded filename</returns> /// <exception cref="System.IO.IOException"/> public static string EncodeJobHistoryFileName(string logFileName) { string replacementDelimiterEscape = null; // Temporarily protect the escape delimiters from encoding if (logFileName.Contains(DelimiterEscape)) { replacementDelimiterEscape = NonOccursString(logFileName); logFileName = logFileName.ReplaceAll(DelimiterEscape, replacementDelimiterEscape); } string encodedFileName = null; try { encodedFileName = URLEncoder.Encode(logFileName, "UTF-8"); } catch (UnsupportedEncodingException uee) { IOException ioe = new IOException(); Sharpen.Extensions.InitCause(ioe, uee); ioe.SetStackTrace(uee.GetStackTrace()); throw ioe; } // Restore protected escape delimiters after encoding if (replacementDelimiterEscape != null) { encodedFileName = encodedFileName.ReplaceAll(replacementDelimiterEscape, DelimiterEscape ); } return(encodedFileName); }
private Stripe.Token CreateToken(string item, string email) { try { GeneralValues objGeneralValues = new GeneralValues(); string plan = item.Split(new String[] { "|||" }, StringSplitOptions.None)[0].ToString(); WifiManager wifiManager = (WifiManager)GetSystemService(Context.WifiService); WifiInfo wInfo = wifiManager.ConnectionInfo; String MACAdress = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId); string amount = item.Split(new String[] { "|||" }, StringSplitOptions.None)[1].ToString(); string id = item.Split(new String[] { "|||" }, StringSplitOptions.None)[2].ToString(); string planid = id; decimal PaymentAmount = Convert.ToDecimal(amount); Dialog paymentdialog = new Dialog(this); paymentdialog.RequestWindowFeature((int)WindowFeatures.NoTitle); paymentdialog.SetContentView(Resource.Layout.Payment); paymentdialog.SetCanceledOnTouchOutside(false); Typeface tf = Typeface.CreateFromAsset(Assets, "Fonts/ROBOTO-LIGHT.TTF"); string encryptedplanname = URLEncoder.Encode(Encrypt(plan), "UTF-8"); string encryptedamount = URLEncoder.Encode(Encrypt(amount), "UTF-8"); string encryptedplanid = URLEncoder.Encode(Encrypt(planid), "UTF-8"); string encrypteduserid = URLEncoder.Encode(Encrypt(empid.ToString()), "UTF-8"); string encryptedmacadress = URLEncoder.Encode(Encrypt(MACAdress), "UTF-8"); string encryptedemailaddress = URLEncoder.Encode(Encrypt(email), "UTF-8"); string url = objGeneralValues.PaymentURL + "?planname=" + encryptedplanname + "&amount=" + encryptedamount + "&planid=" + encryptedplanid + "&user="******"&macaddress=" + encryptedmacadress + "&email=" + encryptedemailaddress; Intent browserintent = new Intent(Intent.ActionView, Android.Net.Uri.Parse("http://59.162.181.91/dtswork/ImInventoryWebPayment/default.aspx?planname=" + encryptedplanname + "&amount=" + encryptedamount + "&planid=" + encryptedplanid + "&user="******"&macaddress=" + encryptedmacadress + "&email=" + encryptedemailaddress)); selecteditempositin = 0; StartActivity(browserintent); } catch (Exception ex) { } return(new Stripe.Token()); }
public void Open(string number) { ValidateOpen(number); var phoneNumber = string.Empty; if (OperatingSystem.IsAndroidVersionAtLeast(24)) { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.GetDefault(Java.Util.Locale.Category.Format).Country) ?? phoneNumber; } else { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.Default.Country) ?? phoneNumber; } // if we are an extension then we need to encode if (phoneNumber.Contains(',', StringComparison.Ordinal) || phoneNumber.Contains(';', StringComparison.Ordinal)) { phoneNumber = URLEncoder.Encode(phoneNumber, "UTF-8") ?? phoneNumber; } var dialIntent = ResolveDialIntent(phoneNumber); var flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; if (OperatingSystem.IsAndroidVersionAtLeast(24)) { flags |= ActivityFlags.LaunchAdjacent; } dialIntent.SetFlags(flags); Application.Context.StartActivity(dialIntent); }
private String requestPaymentStatus(String resourcePath) { if (resourcePath == null) { return null; } URL url; String urlString; HttpURLConnection connection = null; String paymentStatus = null; try { urlString = TravellerApp.Droid.PeachPayment.Common.Constants.BASE_URL + "/status?resourcePath=" + URLEncoder.Encode(resourcePath, "UTF-8"); Log.Debug(TravellerApp.Droid.PeachPayment.Common.Constants.LOG_TAG, "Status request url: " + urlString); url = new URL(urlString); connection = (HttpURLConnection)url.OpenConnection(); connection.ConnectTimeout = TravellerApp.Droid.PeachPayment.Common.Constants.CONNECTION_TIMEOUT; JsonReader jsonReader = new JsonReader( new InputStreamReader(connection.InputStream, "UTF-8")); jsonReader.BeginObject(); while (jsonReader.HasNext) { if (jsonReader.NextName().Equals("paymentResult")) { paymentStatus = jsonReader.NextString(); } else { jsonReader.SkipValue(); } } jsonReader.EndObject(); jsonReader.Close(); Log.Debug(TravellerApp.Droid.PeachPayment.Common.Constants.LOG_TAG, "Status: " + paymentStatus); } catch (Exception e) { Log.Debug(TravellerApp.Droid.PeachPayment.Common.Constants.LOG_TAG, "Error: ", e); } finally { if (connection != null) { connection.Disconnect(); } } return paymentStatus; }
public string GenerateRefreshPostData(string clientSecret, string authCode, string callbackUrl) { return(String.Format("client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=refresh_token&assertion={1}&redirect_uri={2}", URLEncoder.Encode(clientSecret, "utf-8"), URLEncoder.Encode(authCode, "utf-8"), callbackUrl )); }
/// <summary> /// Returns an authenticated /// <see cref="HttpURLConnection"/> /// . If the Delegation /// Token is present, it will be used taking precedence over the configured /// <code>Authenticator</code>. If the <code>doAs</code> parameter is not NULL, /// the request will be done on behalf of the specified <code>doAs</code> user. /// </summary> /// <param name="url">the URL to connect to. Only HTTP/S URLs are supported.</param> /// <param name="token">the authentication token being used for the user.</param> /// <param name="doAs"> /// user to do the the request on behalf of, if NULL the request is /// as self. /// </param> /// <returns> /// an authenticated /// <see cref="HttpURLConnection"/> /// . /// </returns> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// ">if an authentication exception occurred.</exception> public virtual HttpURLConnection OpenConnection(Uri url, DelegationTokenAuthenticatedURL.Token token, string doAs) { Preconditions.CheckNotNull(url, "url"); Preconditions.CheckNotNull(token, "token"); IDictionary <string, string> extraParams = new Dictionary <string, string>(); Org.Apache.Hadoop.Security.Token.Token <TokenIdentifier> dToken = null; // if we have valid auth token, it takes precedence over a delegation token // and we don't even look for one. if (!token.IsSet()) { // delegation token Credentials creds = UserGroupInformation.GetCurrentUser().GetCredentials(); if (!creds.GetAllTokens().IsEmpty()) { IPEndPoint serviceAddr = new IPEndPoint(url.GetHost(), url.Port); Text service = SecurityUtil.BuildTokenService(serviceAddr); dToken = creds.GetToken(service); if (dToken != null) { if (UseQueryStringForDelegationToken()) { // delegation token will go in the query string, injecting it extraParams[KerberosDelegationTokenAuthenticator.DelegationParam] = dToken.EncodeToUrlString (); } else { // delegation token will go as request header, setting it in the // auth-token to ensure no authentication handshake is triggered // (if we have a delegation token, we are authenticated) // the delegation token header is injected in the connection request // at the end of this method. token.delegationToken = (Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier >)dToken; } } } } // proxyuser if (doAs != null) { extraParams[DoAs] = URLEncoder.Encode(doAs, "UTF-8"); } url = AugmentURL(url, extraParams); HttpURLConnection conn = base.OpenConnection(url, token); if (!token.IsSet() && !UseQueryStringForDelegationToken() && dToken != null) { // injecting the delegation token header in the connection request conn.SetRequestProperty(DelegationTokenAuthenticator.DelegationTokenHeader, dToken .EncodeToUrlString()); } return(conn); }
public virtual string GetChangesFeedPath() { if (usePOST) { return("_changes"); } string path = "_changes?feed="; path += GetFeed(); if (mode == ChangeTracker.ChangeTrackerMode.LongPoll) { path += string.Format("&limit=%s", limit); } path += string.Format("&heartbeat=%s", GetHeartbeatMilliseconds()); if (includeConflicts) { path += "&style=all_docs"; } if (lastSequenceID != null) { path += "&since=" + URLEncoder.Encode(lastSequenceID.ToString()); } if (docIDs != null && docIDs.Count > 0) { filterName = "_doc_ids"; filterParams = new Dictionary <string, object>(); filterParams.Put("doc_ids", docIDs); } if (filterName != null) { path += "&filter=" + URLEncoder.Encode(filterName); if (filterParams != null) { foreach (string filterParamKey in filterParams.Keys) { object value = filterParams.Get(filterParamKey); if (!(value is string)) { try { value = Manager.GetObjectMapper().WriteValueAsString(value); } catch (IOException e) { throw new ArgumentException(e); } } path += "&" + URLEncoder.Encode(filterParamKey) + "=" + URLEncoder.Encode(value.ToString ()); } } } return(path); }
public void EncodeClientAdd() { URLEncoder urlEncoder = new URLEncoder(); Client c = new Client(); c.Description = "Prueba"; c.Email = "*****@*****.**"; string expected = "email=javicantos22%40hotmail.es&description=Prueba"; string reply = urlEncoder.Encode<Client>(c); Assert.AreEqual(expected, reply); }
private static string UriEncode(object o) { try { System.Diagnostics.Debug.Assert((o != null), "o canot be null"); return(URLEncoder.Encode(o.ToString(), "UTF-8")); } catch (UnsupportedEncodingException e) { //This should never happen throw new RuntimeException("UTF-8 is not supported by this system?", e); } }
/// <summary> /// Convenience method that creates an HTTP <code>URL</code> for the /// HttpFSServer file system operations. /// </summary> /// <remarks> /// Convenience method that creates an HTTP <code>URL</code> for the /// HttpFSServer file system operations. /// <p/> /// </remarks> /// <param name="path">the file path.</param> /// <param name="params">the query string parameters.</param> /// <param name="multiValuedParams">multi valued parameters of the query string</param> /// <returns>URL a <code>URL</code> for the HttpFSServer server,</returns> /// <exception cref="System.IO.IOException">thrown if an IO error occurs.</exception> internal static Uri CreateURL(Path path, IDictionary <string, string> @params, IDictionary <string, IList <string> > multiValuedParams) { URI uri = path.ToUri(); string realScheme; if (Sharpen.Runtime.EqualsIgnoreCase(uri.GetScheme(), HttpFSFileSystem.Scheme)) { realScheme = "http"; } else { if (Sharpen.Runtime.EqualsIgnoreCase(uri.GetScheme(), HttpsFSFileSystem.Scheme)) { realScheme = "https"; } else { throw new ArgumentException(MessageFormat.Format("Invalid scheme [{0}] it should be '" + HttpFSFileSystem.Scheme + "' " + "or '" + HttpsFSFileSystem.Scheme + "'", uri )); } } StringBuilder sb = new StringBuilder(); sb.Append(realScheme).Append("://").Append(uri.GetAuthority()).Append(ServicePath ).Append(uri.GetPath()); string separator = "?"; foreach (KeyValuePair <string, string> entry in @params) { sb.Append(separator).Append(entry.Key).Append("=").Append(URLEncoder.Encode(entry .Value, "UTF8")); separator = "&"; } if (multiValuedParams != null) { foreach (KeyValuePair <string, IList <string> > multiValuedEntry in multiValuedParams) { string name = URLEncoder.Encode(multiValuedEntry.Key, "UTF8"); IList <string> values = multiValuedEntry.Value; foreach (string value in values) { sb.Append(separator).Append(name).Append("=").Append(URLEncoder.Encode(value, "UTF8" )); separator = "&"; } } } return(new Uri(sb.ToString())); }
public void EncodeClientAdd() { URLEncoder urlEncoder = new URLEncoder(); Client c = new Client(); c.Description = "Prueba"; c.Email = "*****@*****.**"; string expected = "email=javicantos22%40hotmail.es&description=Prueba"; string reply = urlEncoder.Encode <Client>(c); Assert.AreEqual(expected, reply); }
public void EncodeClientUpdate() { URLEncoder urlEncoder = new URLEncoder(); Client c = new Client(); c.Description = "Javier"; c.Email = "*****@*****.**"; c.Id = "client_bbe895116de80b6141fd"; string expected = "email=javicantos33%40hotmail.es&description=Javier&id=client_bbe895116de80b6141fd"; string reply = urlEncoder.Encode<Client>(c); Assert.AreEqual(expected, reply); }
/// <summary>URL encode a value string into an output buffer.</summary> /// <remarks>URL encode a value string into an output buffer.</remarks> /// <param name="urlstr">the output buffer.</param> /// <param name="key">value which must be encoded to protected special characters.</param> public static void Encode(StringBuilder urlstr, string key) { if (key == null || key.Length == 0) { return; } try { urlstr.Append(URLEncoder.Encode(key, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(JGitText.Get().couldNotURLEncodeToUTF8, e); } }
public void EncodeClientUpdate() { URLEncoder urlEncoder = new URLEncoder(); Client c = new Client(); c.Description = "Javier"; c.Email = "*****@*****.**"; c.Id = "client_bbe895116de80b6141fd"; string expected = "email=javicantos33%40hotmail.es&description=Javier&id=client_bbe895116de80b6141fd"; string reply = urlEncoder.Encode <Client>(c); Assert.AreEqual(expected, reply); }
public Response GetDrivingRoutePlanningResult(LatLng latLng1, LatLng latLng2, bool needEncode) { String key = mDefaultKey; if (needEncode) { try { key = URLEncoder.Encode(mDefaultKey, "UTF-8"); } catch (UnsupportedEncodingException e) { e.PrintStackTrace(); } } String url = mDrivingRoutePlanningURL + "?key=" + key; Response response = null; JSONObject origin = new JSONObject(); JSONObject destination = new JSONObject(); JSONObject json = new JSONObject(); try { origin.Put("lat", latLng1.Latitude); origin.Put("lng", latLng1.Longitude); destination.Put("lat", latLng2.Latitude); destination.Put("lng", latLng2.Longitude); json.Put("origin", origin); json.Put("destination", destination); RequestBody requestBody = RequestBody.Create(JSON, json.ToString()); Request request = new Request.Builder().Url(url).Post(requestBody).Build(); response = GetNetClient().InitOkHttpClient().NewCall(request).Execute(); } catch (JSONException e) { e.PrintStackTrace(); } catch (IOException e) { e.PrintStackTrace(); } return(response); }
/** * Example code from http://msdn.microsoft.com/library/azure/dn495627.aspx to * construct a SaS token from the access key to authenticate a request. * * @param uri The unencoded resource URI string for this operation. The resource * URI is the full URI of the Service Bus resource to which access is * claimed. For example, * "http://<namespace>.servicebus.windows.net/<hubName>" */ private static String GenerateSasToken(String uri) { String targetUri; String token = null; try { targetUri = new String(URLEncoder .Encode(uri.ToString().ToLower(), "UTF-8") .ToLower()); long expiresOnDate = JavaSystem.CurrentTimeMillis(); int expiresInMins = 60; // 1 hour expiresOnDate += expiresInMins * 60 * 1000; long expires = expiresOnDate / 1000; String toSign = new String(targetUri + "\n" + expires); // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = HubSasKeyValue.GetBytes("UTF-8"); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.GetInstance("HmacSHA256"); mac.Init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.DoFinal(toSign.GetBytes("UTF-8")); // Using android.util.Base64 for Android Studio instead of // Apache commons codec String signature = new String(URLEncoder.Encode( Base64.EncodeToString(rawHmac, Base64Flags.NoWrap).ToString(), "UTF-8")); // Construct authorization string token = new String("SharedAccessSignature sr=" + targetUri + "&sig=" + signature + "&se=" + expires + "&skn=" + HubSasKeyName); } catch (Exception e) { MainActivity.CurrentActivity.ToastNotify("Exception Generating SaS : " + e.Message.ToString()); //if (isVisible) //{ // ToastNotify("Exception Generating SaS : " + e.getMessage().toString()); //} } return(token); }
public string JoinQuotedEscaped(IList <string> strings) { if (strings.Count == 0) { return("[]"); } byte[] json = null; try { json = Manager.GetObjectMapper().WriteValueAsBytes(strings); } catch (Exception e) { Log.W(Database.Tag, "Unable to serialize json", e); } return(URLEncoder.Encode(Sharpen.Runtime.GetStringForBytes(json))); }
private Stripe.Token CreateToken(string item) { try { GeneralValues objGeneralValues = new GeneralValues(); WebService objWebService = new WebService(); EditText txtemail = FindViewById <EditText>(Resource.Id.txtSignUpEmail); string email = txtemail.Text; plan = item.Split(new String[] { "|||" }, StringSplitOptions.None)[0].ToString(); WifiManager wifiManager = (WifiManager)GetSystemService(Context.WifiService); WifiInfo wInfo = wifiManager.ConnectionInfo; String MACAdress = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId); string amount = item.Split(new String[] { "|||" }, StringSplitOptions.None)[1].ToString(); string id = item.Split(new String[] { "|||" }, StringSplitOptions.None)[2].ToString(); planid = id; PaymentAmount = Convert.ToDecimal(amount); RadioButton rdbBusinessUse = FindViewById <RadioButton>(Resource.Id.rdbBusinessUse); Dialog paymentdialog = new Dialog(this); paymentdialog.RequestWindowFeature((int)WindowFeatures.NoTitle); paymentdialog.SetContentView(Resource.Layout.Payment); paymentdialog.SetCanceledOnTouchOutside(false); Typeface tf = Typeface.CreateFromAsset(Assets, "Fonts/ROBOTO-LIGHT.TTF"); string encryptedplanname = URLEncoder.Encode(Encrypt(plan), "UTF-8"); string encryptedamount = URLEncoder.Encode(Encrypt(amount), "UTF-8"); string encryptedplanid = URLEncoder.Encode(Encrypt(planid), "UTF-8"); string encrypteduserid = URLEncoder.Encode(Encrypt(userid), "UTF-8"); string encryptedmacadress = URLEncoder.Encode(Encrypt(MACAdress), "UTF-8"); string encryptedemailaddress = URLEncoder.Encode(Encrypt(email), "UTF-8"); string url = objGeneralValues.PaymentURL + "?planname=" + encryptedplanname + "&amount=" + encryptedamount + "&planid=" + encryptedplanid + "&user="******"&macaddress=" + encryptedmacadress + "&email=" + encryptedemailaddress; Intent browserintent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(objGeneralValues.PaymentURL + "?planname=" + encryptedplanname + "&amount=" + encryptedamount + "&planid=" + encryptedplanid + "&user="******"&macaddress=" + encryptedmacadress + "&email=" + encryptedemailaddress)); selecteditempositin = 0; if (plan.Trim().ToLower().Contains("platinum")) { objWebService.ExternalSignUpUserSubscriptionAsync(EmployeeID.ToString(), MACAdress, "1", "1", "1"); } else { objWebService.ExternalSignUpUserSubscriptionAsync(EmployeeID.ToString(), MACAdress, "0", "0", "0"); } StartActivity(browserintent); } catch (Exception ex) { } return(token); }
public virtual void TestChangeTrackerWithDocsIds() { Uri testURL = GetReplicationURL(); ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, null); IList <string> docIds = new AList <string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTrackerDocIds.SetDocIDs(docIds); string docIdsEncoded = URLEncoder.Encode("[\"doc1\",\"doc2\"]"); string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s" , docIdsEncoded); string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath(); NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath); }
/// <exception cref="System.IO.IOException"/> private Uri CreateURL(string collection, string resource, string subResource, IDictionary <string, object> parameters) { try { StringBuilder sb = new StringBuilder(); sb.Append(kmsUrl); if (collection != null) { sb.Append(collection); if (resource != null) { sb.Append("/").Append(URLEncoder.Encode(resource, Utf8)); if (subResource != null) { sb.Append("/").Append(subResource); } } } URIBuilder uriBuilder = new URIBuilder(sb.ToString()); if (parameters != null) { foreach (KeyValuePair <string, object> param in parameters) { object value = param.Value; if (value is string) { uriBuilder.AddParameter(param.Key, (string)value); } else { foreach (string s in (string[])value) { uriBuilder.AddParameter(param.Key, s); } } } } return(uriBuilder.Build().ToURL()); } catch (URISyntaxException ex) { throw new IOException(ex); } }
private string GetPostString(Dictionary <string, string> @params) { var _result = new StringBuilder(); foreach (var param in @params) { if (_result.Length() > 0) { _result.Append("&"); } _result.Append(URLEncoder.Encode(param.Key, "UTF-8")); _result.Append("="); _result.Append(URLEncoder.Encode(param.Value, "UTF-8")); } return(_result.ToString()); }
static void PlatformOpen(string number) { ValidateOpen(number); var phoneNumber = string.Empty; #if __ANDROID_24__ if (Platform.HasApiLevelN) { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.GetDefault(Java.Util.Locale.Category.Format).Country) ?? phoneNumber; } else if (Platform.HasApiLevel(BuildVersionCodes.Lollipop)) #else if (Platform.HasApiLevel(BuildVersionCodes.Lollipop)) #endif { phoneNumber = PhoneNumberUtils.FormatNumber(number, Java.Util.Locale.Default.Country) ?? phoneNumber; } else #pragma warning disable CS0618 { phoneNumber = PhoneNumberUtils.FormatNumber(number) ?? phoneNumber; } #pragma warning restore CS0618 // if we are an extension then we need to encode if (phoneNumber.Contains(',') || phoneNumber.Contains(';')) { phoneNumber = URLEncoder.Encode(phoneNumber, "UTF-8") ?? phoneNumber; } var dialIntent = ResolveDialIntent(phoneNumber); var flags = ActivityFlags.ClearTop | ActivityFlags.NewTask; #if __ANDROID_24__ if (Platform.HasApiLevelN) { flags |= ActivityFlags.LaunchAdjacent; } #endif dialIntent.SetFlags(flags); Platform.AppContext.StartActivity(dialIntent); }
public static string BuildPath(string journalId, long segmentTxId, NamespaceInfo nsInfo) { StringBuilder path = new StringBuilder("/getJournal?"); try { path.Append(JournalIdParam).Append("=").Append(URLEncoder.Encode(journalId, "UTF-8" )); path.Append("&" + SegmentTxidParam).Append("=").Append(segmentTxId); path.Append("&" + StorageinfoParam).Append("=").Append(URLEncoder.Encode(nsInfo.ToColonSeparatedString (), "UTF-8")); } catch (UnsupportedEncodingException e) { // Never get here -- everyone supports UTF-8 throw new RuntimeException(e); } return(path.ToString()); }
/// <summary> /// 支付动作 /// </summary> public void Pay(String subject, String body, decimal money) { try { var con = GetOrderInfo(subject, body, money); // 特别注意,这里的签名逻辑需要放在服务端,切勿将私钥泄露在代码中! var sign = SignatureUtils.Sign(con, rsa_private); sign = URLEncoder.Encode(sign, "UTF-8"); con += "&sign=\"" + sign + "\"&" + MySignType; Com.Alipay.Sdk.App.PayTask pa = new Com.Alipay.Sdk.App.PayTask(context); // con = "partner=\"2088101568358171\"&seller_id=\"[email protected]\"&out_trade_no=\"YR2VGG3G1I31XDZ\"&subject=\"1\"&body=\"我是测试数据\"&total_fee=\"0.01\"¬ify_url=\"http://111.203.248.34:89/Order/AlipayNotify\"&service=\"mobile.securitypay.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&sign=\"GsSZgPloF1vn52XAItRAldwQAbzIgkDyByCxMfTZG%2FMapRoyrNIJo4U1LUGjHp6gdBZ7U8jA1kljLPqkeGv8MZigd3kH25V0UK3Jc3C94Ngxm5S%2Fz5QsNr6wnqNY9sx%2Bw6DqNdEQnnks7PKvvU0zgsynip50lAhJmflmfHvp%2Bgk%3D\"&sign_type=\"RSA\""; Logger_Info(con); var result = pa.Pay(con, false); Logger_Info("支付宝result:" + result); //调用结果查看result中是否返回是90000,如果是,则成功 } catch (Exception ex) { Logger_Info("2" + ex.Message + ex.StackTrace); } }
/** * 拼接键值对 * * @param key * @param value * @param isEncode * @return */ private static string BuildKeyValue(string key, string value, bool isEncode) { StringBuilder sb = new StringBuilder(); sb.Append(key); sb.Append("="); if (isEncode) { try { sb.Append(URLEncoder.Encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { sb.Append(value); } } else { sb.Append(value); } return(sb.ToString()); }
public void PullRemoteRevision(RevisionInternal rev) { Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread().ToString() + ": pullRemoteRevision with rev: " + rev); Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": pullRemoteRevision() calling asyncTaskStarted()" ); AsyncTaskStarted(); ++httpConnectionCount; // Construct a query. We want the revision history, and the bodies of attachments that have // been added since the latest revisions we have locally. // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document StringBuilder path = new StringBuilder("/" + URLEncoder.Encode(rev.GetDocId()) + "?rev=" + URLEncoder.Encode(rev.GetRevId()) + "&revs=true&attachments=true"); IList <string> knownRevs = KnownCurrentRevIDs(rev); if (knownRevs == null) { //this means something is wrong, possibly the replicator has shut down Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": pullRemoteRevision() calling asyncTaskFinished()" ); AsyncTaskFinished(1); --httpConnectionCount; return; } if (knownRevs.Count > 0) { path.Append("&atts_since="); path.Append(JoinQuotedEscaped(knownRevs)); } //create a final version of this variable for the log statement inside //FIXME find a way to avoid this string pathInside = path.ToString(); SendAsyncMultipartDownloaderRequest("GET", pathInside, null, db, new _RemoteRequestCompletionBlock_336 (this, rev, pathInside)); }
/// <summary>Convert the parameters to a sorted String.</summary> /// <param name="separator">URI parameter separator character</param> /// <param name="parameters">parameters to encode into a string</param> /// <returns>the encoded URI string</returns> public static string ToSortedString(string separator, params Org.Apache.Hadoop.Hdfs.Web.Resources.Param <object, object>[] parameters) { Arrays.Sort(parameters, NameCmp); StringBuilder b = new StringBuilder(); try { foreach (Org.Apache.Hadoop.Hdfs.Web.Resources.Param <object, object> p in parameters) { if (p.GetValue() != null) { b.Append(separator).Append(URLEncoder.Encode(p.GetName(), "UTF-8") + "=" + URLEncoder .Encode(p.GetValueString(), "UTF-8")); } } } catch (UnsupportedEncodingException e) { // Sane systems know about UTF-8, so this should never happen. throw new RuntimeException(e); } return(b.ToString()); }
/** * 对支付参数信息进行签名 * * @param map * 待签名授权信息 * * @return */ public static string GetSign(Dictionary <string, string> map, string rsaKey, bool rsa2) { List <string> keys = new List <string>(map.Keys); // key排序 Collections.Sort(keys); StringBuilder authInfo = new StringBuilder(); for (int i = 0; i < keys.Count - 1; i++) { string key = keys[i]; string value = map[key]; authInfo.Append(BuildKeyValue(key, value, false)); authInfo.Append("&"); } string tailKey = keys[keys.Count - 1]; string tailValue = map[tailKey]; authInfo.Append(BuildKeyValue(tailKey, tailValue, false)); string auth = authInfo.ToString(); string oriSign = SignUtils.Sign(auth, rsaKey, rsa2); string encodedSign = ""; try { encodedSign = URLEncoder.Encode(oriSign, "UTF-8"); } catch (UnsupportedEncodingException e) { e.PrintStackTrace(); } return("sign=" + encodedSign); }