Search code examples
javaangulardevelopment-environmenturlencodeproduction-environment

How to fix URLEncoder related issues?


I am having issues with my URL encoder, it is working locally and on stage, but not working on live.

I am using filters to get brand names, but some of those brand names have spaces. When I send a request on live, it returns a 500 error.

java.net.URISyntaxException: Illegal character in query at index 236:
http://gateway-service/deal-solution-service/api/deals?categories=false&phonesAndSim=false&lteAndSim=false&tabletsAndLaptops=false&connectivity=false&priceMin=0&priceMax=50000&duration36=false&duration24=false&brand=Huawei Spa

It was supposed to take care of this "Huawei Spa"

my serviceImpl:

@Override
public Collection<String> getDistinctBrands(Filter1 productFilter) {
    List<String> distinctBrands = new ArrayList<>();

    if (productFilter != null && productFilter.getBrand() != null && !productFilter.getBrand().isEmpty()) {
        String encodedBrand = URLEncoder.encode(productFilter.getBrand(), StandardCharsets.UTF_8);
        distinctBrands.addAll(Arrays.asList(encodedBrand.split("[^a-zA-Z0-9\\-_']+")));
    } else {
        distinctBrands = dealRepository.findDistinctBrands();
    }
    return distinctBrands;
} 

my controller:

@Override
public ResponseEntity<List<String>> getDistinctBrands(Filter1 filter) {
    Collection<String> distinctBrands = dealService.getDistinctBrands(filter);
    if (!distinctBrands.isEmpty()) {
        List<String> decodedBrands = new ArrayList<>();
        for (String brand : distinctBrands) {
            decodedBrands.add(URLDecoder.decode(brand, StandardCharsets.UTF_8));
        }
        return ResponseEntity.ok(decodedBrands);
    } else {
        return ResponseEntity.notFound().build();
    }
}

I was having issues when using filters (filtering by brand name with spaces), I then added a URL encoder, and it started working locally and on the staging environment, but it still didn't work on live.

If my brand name contains spaces, I want to encode my URL to fill in the spaces.


Solution

  • based on the description and snippets, your approach to url encoding seems to be more or less correct. The error you are seeing indicates that there is an issue with white space encoding.

    When you encode a string like "Huawei Spa" spaces should be replaced with '+' or '%20'. You can encode it here and test on your environment.

    The fact that it works locally and not on production may indicate discrepancy in how URLs are interpreted across those environments. Everything between client and the app, including server, reverse proxies and other configurations can cause such behavior.

    For URLEncoder reference please check official documentation