I have a Spring Boot Java application that exchanges data with an external API using a Feign client. This API only accepts data encoded in Windows-1251 for non-Latin characters. I have configured my Feign client to send the data, and it works fine when it consists of Latin characters only. However, when I need to transfer mixed data, it encodes using Percent Encoding.
Here is an example:
The string parameter I need to transfer: Тест
The Windows-1251 and then Percent Encoding representation of that string (the desired option): %D2%E5%F1%F2
The Percent Encoding representation of that string only (the received option): %D0%A2%D0%B5%D1%81%D1%82
I have created a test Java project that encodes the data the way I need it to be encoded.:
import java.nio.charset.Charset;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Main {
public static void main(String[] args) {
String input = "Тест";
String encoded = encodeToCP1251(input);
String percentEncoded = percentEncode(encoded);
System.out.println(percentEncoded); // %D2%E5%F1%F2
}
public static String encodeToCP1251(String input) {
byte[] bytes = input.getBytes(Charset.forName("CP1251"));
return new String(bytes, Charset.forName("CP1251"));
}
public static String percentEncode(String input) {
try {
return URLEncoder.encode(input, "CP1251");
} catch (UnsupportedEncodingException e) {
// Handle encoding exception
e.printStackTrace();
return null;
}
}
}
Here is the configuration of my Feign client:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.majordomo.hms.domainregistrar.config.FeignConfig;
import java.util.Map;
@FeignClient(name = "test", configuration = FeignConfig.class, url = "https://localhost")
public interface FeignClient {
@PostMapping("/test")
String sendRequest(@RequestParam Map<String, String> requestData);
}
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.BASIC;
}
}
How can I properly encode @RequestParam param data the way I need it and send to external API?
Tried different ways of encoding the data suggested by OpenAI & Stack Overflow, but nothing worked