如何自己做非 GET 请求 API
How to do non-GET requests on your own API
我按照 this 指南创建了自己的 REST API。我正在尝试使用我根据指南构建的 API,但在使用任何不是 GET
请求的请求时,我 运行 遇到了一些麻烦。当我尝试执行删除请求时。 (http://localhost:8080/api/v1/employees/3
)
我会得到一个 405 error
但我不确定为什么(我的本地主机没有任何密码保护)。我想了解如何创建 GET
以外的请求。我尝试为我的 POST
请求使用查询参数,但没有成功。
我查看了所有其他 Whosebug 类似问题,但找不到任何内容。
EDIT1:我正在使用一个简单的 Java 应用程序来执行此操作。
这是我用来执行 GET
请求的代码
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);
}
您可以使用 org.springframework.web.client.RestTemplate(休息模板)来消耗休息 api。
对于删除,你可以这样做
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);
}
请检查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
希望这些能提供足够的信息
尝试替换这个URLConnection conn = url.openConnection();
对此:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
我按照 this 指南创建了自己的 REST API。我正在尝试使用我根据指南构建的 API,但在使用任何不是 GET
请求的请求时,我 运行 遇到了一些麻烦。当我尝试执行删除请求时。 (http://localhost:8080/api/v1/employees/3
)
我会得到一个 405 error
但我不确定为什么(我的本地主机没有任何密码保护)。我想了解如何创建 GET
以外的请求。我尝试为我的 POST
请求使用查询参数,但没有成功。
我查看了所有其他 Whosebug 类似问题,但找不到任何内容。
EDIT1:我正在使用一个简单的 Java 应用程序来执行此操作。
这是我用来执行 GET
请求的代码
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);
}
您可以使用 org.springframework.web.client.RestTemplate(休息模板)来消耗休息 api。
对于删除,你可以这样做
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);
}
请检查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
希望这些能提供足够的信息
尝试替换这个URLConnection conn = url.openConnection();
对此:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");