I have a Json String to encode
String strMappingList = [{"Id": "67","AccessType": "2"},{"Id": "1111","AccessType": "2"},{"Id": "1166","AccessType": "2"}]
When I did url encoding it encodes strMappingList twice
try {
String str = URLEncoder.encode(strMappingList, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Try the code you take in strings file
if you get response from server that fine not use in string.xml you use direct
in string.xml
<string name="urls">[{"Id": "67","AccessType": "2"},{"Id": "1111","AccessType": "2"},{"Id": "1166","AccessType": "2"}]</string>
Code
String strMappingList = getResources().getString(R.string.urls);
try {
String str = URLEncoder.encode(strMappingList, "UTF-8");
System.out.println("Strings"+str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Output Single time
%5B%7BId%3A+67%2CAccessType%3A+2%7D%2C%7BId%3A+1111%2CAccessType%3A+2%7D%2C%7BId%3A+1166%2CAccessType%3A+2%7D%5D
Related
In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))
I am trying to convert this 64 based encoded JSON string and convert received JSON into POJO using flexjson API.
First try block, converts direct JSON as string into object which is success. This string is decoded using online tool.
Now second try block, try to convert 64 based string into an object in a similar way but converting the 64based string on the run which is throwing exception flexjson.JSONException: Expected a ',' or ']' at character 10
try {
AsyncResponseDO asyncResponseDO = new JSONDeserializer<AsyncResponseDO>().deserialize("{\"relatesTo\":\"7_Sept2017_IF01\"}", AsyncResponseDO.class);
System.out.println(asyncResponseDO.getRelatesTo());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
AsyncResponseDO asyncResponseDO = new JSONDeserializer<AsyncResponseDO>().deserialize(Base64.decodeBase64("eyJyZWxhdGVzVG8iOiI3X1NlcHQyMDE3X0lGMDEifQ==".getBytes()).toString(), AsyncResponseDO.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POJO class :
public class AsyncResponseDO {
private String relatesTo;
public String getRelatesTo() {
return relatesTo;
}
public void setRelatesTo(String relatesTo) {
this.relatesTo = relatesTo;
}
}
new String(Base64.decodeBase64("eyJyZWxhdGVzVG8iOiI3X1NlcHQyMDE3X0lGMDEifQ==".getBytes()));
This will convert into a proper string.
I referred to https://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/
I want a url that will look like this
"http://example.com/get_item_data.php?uid="inv_no"
I tried URL encoder, but could not figure it out,
I first tried this, it did not work
try {
json_url = "http://example.com/get_item_data.php?uid="+ URLEncoder.encode(inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
then this
try {
json_url = "http://example.com/get_item_data.php?uid="+ URLEncoder.encode("inv_no", "UTF-8") + "=" + URLEncoder.encode(inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
yet, no result, please help
Usually you don't have to quote your parameters. So to me your first trial is correct:
json_url = "http://example.com/get_item_data.php?uid="+
URLEncoder.encode( inv_no, "UTF-8");
Not sure about what you're trying to do, but looking at your question I suggest the following code:
try {
json_url = "http://example.com/get_item_data.php?uid=\""+
URLEncoder.encode( inv_no, "UTF-8") + "\"";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
In this case you have the quote outside the encoded parameter inv_no.
Or even:
try {
json_url = "http://example.com/get_item_data.php?uid="+
URLEncoder.encode("\"" + inv_no + "\"", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
In this case the parameter inv_no and the quotes will be encoded.
try {
String json_url = "\"http://example.com/get_item_data.php?uid=\"inv_no\"";
System.out.println(json_url);
} catch (Exception e) {
e.printStackTrace();
}
Encode the whole string AFTER you added your ´inv_no´-variable.
try {
json_url = URLEncoder.encode('http://example.com/get_item_data.php?uid='+inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
having some serious problem when trying to read a local JSON file. I've looked everywhere for many days now and the best and farthest I could get was copying from Faizan's answer.
Reading a json file in Android
How come that Android Studio doesn't let me generate the second try-catch code block here?
Help and advice are very much appreciated!!
This is My code
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("names.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
How come that Android Studio doesn't let me generate the second
try-catch code block here?
Simply, because your code is not inside a method.
Doing something like below should solve the error.
public void someMethodIdentifier(){ // doesn't have to be void return type, you know better than me what type you want to return.
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
Note - from the looks of the statements that's contained within the try block I think you intended to return some data? if that's the case just replace the void return type with the appropriate return type and return that data.
In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))