Reputation: 695
I followed this guide to create my own REST API. I am trying to consume my API that I built from the guide but I ran into some trouble when it came to using any request that wasn't a GET
request. When I tried doing a delete request. (http://localhost:8080/api/v1/employees/3
)
I would get a 405 error
and I'm not sure why (I do not have any password protection in my local host). I want to understand how I can create requests other than GET
. I tried using query parameters for my POST
request, but it was unsuccessful.
I looked at all the other StackOverFlow Similar Questions and I couldn't find anything.
EDIT1: I am using a simple Java Application to do this.
This was the code I used in order to do my GET
requests
String urlString = "http://localhost:8080/api/v1/employees";
try {
String result = "";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader (new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result += line;
}
rd.close();
System.out.println(result);
}
Upvotes: 0
Views: 140
Reputation: 1052
Try to replace this URLConnection conn = url.openConnection();
to this:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Upvotes: 3
Reputation: 11
you can use org.springframework.web.client.RestTemplate (rest-template) to consume rest api.
for delete, you can do something like
private void deleteEmployee() {
Map < String, String > params = new HashMap < String, String > ();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
}
please check https://www.javaguides.net/2019/06/spring-resttemplate-get-post-put-and-delete-example.html and https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html and https://www.baeldung.com/rest-template
hope these provide enough info
Upvotes: 1