URL encoding is getting failed for special character. #Android

Viewed 972

I'm working on a solution where need to encode string into utf-8 format, this string nothing but device name that I'm reading using BluetoothAdapter.getDefaultAdapter().name.

For one of sampple I got a string like ABC-& and encoding this returned ABC-%EF%BC%86 instead of ABC-%26. It was weird until further debugging which helped to identify that there is difference between & and &. Second one is some other character which is failing to encoded as expected.

& and & both are different.

For encoding tried both URLEncoder.encode(input, "utf-8") and Uri.encode(input, "utf-8") but nothing worked.

This is just an example, there might be other character which may look like same as actual character but failed to encode. Now question are:

  1. Why this difference, after all it is reading of some data from device using standard SDK API.
  2. How can fix this be fixed. Find and replace with actual character could be a approach but scope is limited, there might be other unknown character.

Any suggestion around !!

1 Answers

One solution would be to define your allowed character scope. Then either replace or remove the characters that fall outside of this scope.

Given the following regex:

[a-zA-Z0-9 -+&#]

You could then either do:

input.replaceAll("[a-zA-Z0-9 -+&#]", "_");

...or if you don't care about possibly empty results:

input.replaceAll("[a-zA-Z0-9 -+&#]", "");

The first approach would give you a length-consistent representation of the original Bluetooth device name.

Either way, this approach has worked wonders for me and my colleagues. Hope this could be of any help .

Related