== How to fix it in Java SE

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
@GetMapping("/user")
public String getUser(@RequestParam(value = "id") String id) {
    URL url = new URL("http://example.com/api/user/" + id); // Noncompliant
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@GetMapping("/user")
public String getUser(@RequestParam(value = "id") String id) {
    String encodedId = URLEncoder.encode(id, StandardCharsets.UTF_8);
    URL url = new URL("http://example.com/api/user/?id=" + encodedId);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
}
----

=== How does this work?

include::../../common/fix/encoding.adoc[]
