1

I have a String with the character "Á" (spanish language) and I have some problem with the request to the API.

In this way I get the 400 ERROR BAD REQUEST

String address = "Ángel Marsa I Becá è";
String encoded = new String(address.getBytes("UTF-8"));
System.out.println(encoded);//�ngel Marsa I Becá è

Using antoher manner to encode, with ISO-8859-1 and then UTF-8 I don't get the BAD REQUEST 400 ERROR.

byte ptext[] = address.getBytes("ISO-8859-1"); 
String value = new String(ptext, "UTF-8");
System.out.println(value);//?ngel Marsa I Bec? ?

Is this way encoded UTF8 correctly?

Which is the best way to encode to UTF-8, specially strings with accents, or with "ñ".

Thanks

proera
  • 123
  • 1
  • 3
  • 14
  • 2
    "Is this way encoded UTF8 correctly?" No, not at all. It has nothing to do with encoding, and in many cases it will destroy the String (as you can see in your examples, both of them destroy the String). In the **best** case it doesn't do anything to the String. See [here](https://stackoverflow.com/questions/29667977/converting-string-from-one-charset-to-another) for more info, and explanation on your "encoding" and why it can never work. – Kayaman Mar 10 '20 at 11:32
  • @Kayaman So is impossible to encode to UTF-8, strings with accents? – proera Mar 10 '20 at 11:35
  • Not at all, but your problem isn't related to that. You're getting an error from the API, but your attempted solution will never work. It's not the String you need to worry about, it's how you're making the call to the API. – Kayaman Mar 10 '20 at 11:40
  • @Kayaman The API returns the 400 error bad request because my request is malformed (because of the accents). For example, if I have a JSON with a string without any accent I don't get errors. So, how can I make the request with a string that containts accents? – proera Mar 10 '20 at 11:44
  • 1
    JSON should be UTF8. I have no idea how you're making your requests, but apparently you're not making them correctly since they're not in UTF8. So fix your request code, your Strings are fine. – Kayaman Mar 10 '20 at 11:50
  • 2
    Can you post your code that actually makes this request? Do you perform transcoding anywhere else? – Thomas Timbul Mar 10 '20 at 13:42

2 Answers2

1

You can use java.net.URLEncoder to pass strings that are not otherwise acceptable in the URL.

String s = "Ángel Marsa I Becá è";
String e = URLEncoder.encode(s, "UTF-8");
System.out.println(e);

This will look like %C3%81ngel+Marsa+I+Bec%C3%A1+%C3%A8.

Once you get it over the network, you always can restore original text with UrlDecoder.decode.

tentacle
  • 543
  • 1
  • 3
  • 8
0

I was missing the parameter charset=utf-8 to the Content-Type.

proera
  • 123
  • 1
  • 3
  • 14