int a=50;
How do I encode this using URLEncoder?
For strings we do
String value=URLEncoder.encoder("SomeStringValye",this.encoding);
Integer numbers in the URL are not an issue. You need not URL encode it.
So in your case, simply construct a url by concatenating as follows
String s = "www.xyz.com/?id=" +1;
If you have some special characters in your url parameter like space, ;, then you have to url encode the parameter value
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString() )
If you still want to pass the integer to the URL encoder method, simply make your integer as a string e.g., 10+""
Related
I have a unit test I was trying to write for a generateKey(int **length**) method. The method:
1. Creates a byte array with size of input parameter length
2. Uses SecureRandom().nextBytes(randomKey) method to populate the byte array with random values
3. Encodes the byte array filled with random values to a UTF-8 String object
4. Re-writes the original byte array (called randomKey) to 0's for security
5. Returns the UTF-8 encoded String
I already have a unit test checking for the user inputting a negative value (i.e. -1) such that the byte array would throw a Negative array size exception.
Would a good positive test case be to check that a UTF-8 encoded String is successfully created? Is there a method I can call on the generated String to check that it equals "UTF-8" encoding?
I can't check that the String equals the same String, since the byte array is filled with random values each time it is called....
source code is here:
public static String generateKey(int length) {
byte[] randomKey = new byte[length];
new SecureRandom().nextBytes(randomKey);
String key = new String(randomKey, Charset.forName("UTF-8"));//Base64.getEncoder().encodeToString(randomKey);
Arrays.fill(randomKey,(byte) 0);
return key;
}
You can convert a UTF8 string to a byte array as below
String str = "私の"; // replace this with your generateKey result
byte [] b = str.getBytes();
String newString;
try {
newString = new String (b, "UTF-8");
System.out.println(newString);
System.out.println("size is equal ? " + (str.length() == newString.length()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
First, the code you posted is simply wrong: you can't take a random array of bytes and treat it as a UTF-8 string, because UTF-8 expects certain bit patterns to indicate multi-byte characters.
Unfortunately, this failure happens silently, because you're using a string constructor that "always replaces malformed-input and unmappable-character sequences with this charset's default replacement string". So you'll get something, but you wouldn't be able to translate it back to the same binary value.
The comment in the code, however, gives you the answer: you need to use Base64 to encode the binary value.
However, that still won't let you verify that the encoded string is equivalent to the original byte array, because the function takes great care to zero out the array immediately after use (which doesn't really do what the author thinks it does, but I'm not going to get into that argument).
If you really want to test a method like this, you need to be able to mock out core parts of it. You could, for example, separate out the generation of random bytes from encoding, and then pass in a byte generator that keeps track of the bytes that it generated.
But the real question is why? What are you (or more correctly, the person writing this code) actually trying to accomplish? And why won't a UUID accomplish it?
Hello I have a url string like
http://example.com/foo/?bar=15&oof=myp
Now lets say that I want to change the int value in the bar parameter to 16, in order to have
http://example.com/foo/?bar=16&oof=myp
How can I do this? Considering that the number after the = might be of 1, 2 or ever 3 characters. Thank you
You can use UriComponentsBuilder (it's part of Spring Web jar) like this:
String url = "http://example.com/foo/?bar=15&oof=myp";
UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(url);
urlBuilder.replaceQueryParam("bar", 107);
String result = urlBuilder.build().toUriString();
Substitute 107 with the number you want. With this method you can have URI or String object from urlBuilder.
Use regex to find the number parameter in the string url
Use String.replace() to replace the old parameter with the new parameter
String classs = "java1110======$500.50";
and I want to extract 500.50 from the String value. What should I do?
I tried replace() but it gives me 111050050.
try this :
class.substring(class.lastIndexOf("$") + 1);
Use the ASCII range of numbers to set up the condition that whenever the ASCII value of a particular character comes up in between you put it in a character array,or any string variable,it's all on your discretion.
Hope this helps
I have an application that get som Strings by JSON.
The problem is that I think that they are sending it as ASCII and the text really should be in unicode.
For example, there are parts of the string that is "\u00f6" which is the swedish letter "ö"
For example the swedish word for "buy" is "köpa" and the string I get is "k\u00f6pa"
Is there an easy way for me after I recived this String in java to convert it to the correct representation?
That is, I want to convert strings like "k\u00f6pa" to "köpa"
Thank for all help!
Well, that is easy enough, just use a JSON library. With Jackson for instance you will:
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(your, source, here);
The JsonNode will in fact be a TextNode; you can just retrieve the text as:
node.textValue()
Note that this IS NOT an "ASCII representation" of a String; it just happens that JSON strings can contain UTF-16 code unit character escapes like this one.
(you will lose the quotes around the value, though, but that is probably what you expect anyway)
The hex code is just 2 bytes of integer, which an int can handle just fine -- so you can just use Integer.parse(s, 16) where s is the string without the "\u" prefix. Then you just narrow that int to a char, which is guaranteed to fit.
Throw in some regex (to validate the string and also extract the hex code), and you're all done.
Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
Matcher m = p.matcher(arg);
if (m.matches()) {
String code = m.group(1);
int i = Integer.parseInt(code, 16);
char c = (char) i;
System.out.println(c);
}
Is there a way to find the same integer/long or any digit number equivalent to a given string using java.
e.g If i give a string "Java_programming" it should give me always something like "7287272" digit.
The generated digit/number should be unique i.e. it should always generate "123" for "xyz" not "123" for "abc".
Call the hashCode method of your String object.
I.e :
String t = "Java_programming";
String t2 = "Java_programming";
System.out.println(t.hashCode());
System.out.println(t2.hashCode());
Gives :
748582308
748582308
Using hashCode in this case will meet your requirements (as you formuled it) but be careful, two different String can produce the SAME hashCode value ! (see #Dirk example)
What are your requirements? You could just use a new BigInteger("somestring".toBytes("UTF-8")).toString() to convert the string to a number, but will it do what you want?
Why don't you create a SHA-1 out of the string and use that as a key?
static HashFunction hashFunction = Hashing.sha1();
public static byte[] getHash(final String string) {
HashCode hashCode = hashFunction.newHasher().putBytes(string.getBytes).hash();
return hashCode.asBytes();
}
You can then do Bytes.toInt(hash) or Bytes.toLong(hash)
Yes, it is possible. You can use String.hashCode() method on string.
Here you find more details how integer returned by this method is created
It depends if you want that 2 different String have to give always 2 different identifiers.
String.hashCode() can do what you want, the same string will give always the same ID but 2 different strings can also give the same ID.
If you want a unique identifier you can i.e. concatenate each byte character value from your string.
First take your string and convert it to a sequence of bytes:
String a = "hello";
byte[] b = a.getBytes();
Now convert the bytes to a numeric representation, using BigInteger
BigInteger c = new BigInteger(b);
Finally, convert the BigInteger back to a string using its toString() method
String d = c.toString();
You are guaranteed to get the same output for the same input, and different outputs for different inputs. You can combine all of these into one step by doing
String d = new BigInteger(a.getBytes()).toString();