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

asked Mar 10, 2020 at 11:26
6
  • 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 for more info, and explanation on your "encoding" and why it can never work. Commented Mar 10, 2020 at 11:32
  • @Kayaman So is impossible to encode to UTF-8, strings with accents? Commented Mar 10, 2020 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. Commented Mar 10, 2020 at 11:40
  • 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. Commented Mar 10, 2020 at 11:50
  • 2
    Can you post your code that actually makes this request? Do you perform transcoding anywhere else? Commented Mar 10, 2020 at 13:42

2 Answers 2

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.

answered Mar 10, 2020 at 16:54
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Mar 11, 2020 at 10:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.