Я столкнулся с вопросами, как это в прошлом с определенными рамками. Мне не хватает вашего кода, чтобы точно знать, но что может произойти - это какая-то инфраструктура, которую вы используете, в моем случае это была весна, снова кодирует URL. Я провел несколько дней, пытаясь решить аналогичную проблему, когда я думал, что строка заменена, и URI.builder() был сломан. В результате проблема заключалась в том, что моя инфраструктура http взяла мой закодированный URL-адрес и снова закодировала его. это означает, что в любом месте, где он видел «% 20», он увидит «%» charictor и переключится на «%» http-код «% 25», в результате чего появится «% 2520». Тогда запрос будет терпеть неудачу, потому что% 2520 не переводится в пространство, которое ожидал мой сервер. В то время как проблема, похоже, была одной из моих кодов не работает, это было действительно вопрос кодирования слишком много раз. У меня есть пример из некоторых рабочего кода в одном из моих проектов ниже
//the Url of the server
String fullUrl = "http://myapiserver.com/path/";
//The parameter to append. contains a space that will need to be encoded
String param 1 = "parameter 1"
//Use Uri.Builder to append parameter
Uri.Builder uriBuilder = Uri.parse(fullUrl).buildUpon();
uriBuilder.appendQueryParameter("parameter1",param1);
/* Below is where it is important to understand how your
http framework handles unencoded url. In my case, which is Spring
framework, the urls are encoded when performing requests.
The result is that a url that is already encoded will be
encoded twice. For instance, if you're url is
"http://myapiserver.com/path?parameter1=param 1"
and it needs to be read by the server as
"http://myapiserver.com/path?parameter1=param%201"
it makes sense to encode the url using URI.builder().append, or any valid
solutions listed in other posts. However, If the framework is already
encoding your url, then it is likely to run into the issue where you
accidently encode the url twice: Once when you are preparing the URL to be
sent, and once again when you are sending the message through the framework.
this results in sending a url that looks like
"http://myapiserver.com/path?parameter1=param%25201"
where the '%' in "%20" was replaced with "%25", http's representation of '%'
when what you wanted was
"http://myapiserver.com/path?parameter1=param%201"
this can be a difficult bug to squash because you can copy the url in the
debugger prior to it being sent and paste it into a tool like fiddler and
have the fiddler request work but the program request fail.
since my http framework was already encoding the urls, I had to unencode the
urls after appending the parameters so they would only be encoded once.
I'm not saying it's the most gracefull solution, but the code works.
*/
String finalUrl = uriBuilder.build().toString().replace("%2F","/")
.replace("%3A", ":").replace("%20", " ");
//Call the server and ask for the menu. the Menu is saved to a string
//rest.GET() uses spring framework. The url is encoded again as
part of the framework.
menuStringFromIoms = rest.GET(finalUrl);
Существует вероятность более изящный способ сохранить URL из кодирующих дважды. Надеюсь, этот пример поможет вам в правильном направлении или устранить возможность. Удачи.
В String нет метода 'replace (char, String)'. Вы можете попробовать с помощью 'replace (String, String)'. Помните, что '' 'может обернуть только один символ, а' '' представляет строку. – Pshemo
вы можете попробовать 'imageUrl.replace (" \\ s ","% 20 ");' –
@ Amit.rk3 'replace' doesn ' t используйте синтаксис regex. Вы можете изменить его на 'replaceAll'. – Pshemo