Common Java Practice Problems
java.net.URISyntaxException: Illegal character in path at index 49
with Illegal Character in Path when i am going to call Rest API using Java 11 HttpClient.
Mostly the reason of this error is url contains empty space (" ").
in my case
url="http://localhost:8080/api/customers/byname"+name;
Some reason when i get to call Get Api from my java class which is as follows
public static HttpResponse callRestApiGet(String url)
{
try {
request =HttpRequest.newBuilder(URI.create(url))
.
header("Content-Type", "application/json")
.
GET().build();
response = null;
response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e)
{
e.printStackTrace();
return null;
} catch (URISyntaxException e)
{ e.printStackTrace();
return null;
}
}
And my Test class As follows
public class Test
{
public static void main(String[] args)
{
CustomerService service = new CustomerService();
String name = "Ankush Sawaleram Supnar";
System.out.println(service.getCustomerByName(name));
}
}
But it shows me the error
URISyntaxException with Illegal Character in Path
"http://localhost:8080/api/customers/byname/Ankush Sawaleram Supnar"
When i called this url from my browser and also in Postman it shows me the correct result.
Solution for this problem is replace space from our String variable to %20 mostly used for white spaces.
name = name.replace(" ", "%20");
and then our url is as follows:
url= "http://localhost:8080/api/customers/byname/Ankush%20Sawaleram%20Supnar";
This way my problem is solved.
Thank you for reading my Post.
Comments
Post a Comment