- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个访问 MySQL 数据库的 Web 服务,但是当我尝试删除记录时,我总是得到以下返回:
HTTP 状态 405 - 不允许的方法。源服务器已知请求行中收到的方法,但目标资源不支持。
当我在数据库控制台上运行相同的查询时,记录被删除。我看到几个教程都用同样的方式使用@DELETE方法,我找不到原因。
这是我的 WS 的代码:
package ws;
import com.google.gson.Gson;
import dao.PokemonDAO;
import dao.TrainerDAO;
import java.util.ArrayList;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import model.Pokemon;
import model.Trainer;
/**
* REST Web Service
*
* @author sandrini
*/
@Path("pokews")
public class PokedexWebService {
PokemonDAO pokemonDAO = new PokemonDAO();
TrainerDAO trainerDAO = new TrainerDAO();
@Context
private UriInfo context;
/**
* Creates a new instance of PokedexWebService
*/
public PokedexWebService() {
}
/**
* Retrieves representation of an instance of teste.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Produces(MediaType.APPLICATION_XML)
public String getXml() {
//TODO return proper representation object
throw new UnsupportedOperationException();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/list")
public ArrayList pokeList() {
return pokemonDAO.listPokemon();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/fetch/{id}")
public Pokemon pokeFetch(@PathParam("id") int id) {
return pokemonDAO.fetchPokemon(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/isFavorite/{id}")
public String pokeIsFavorite(@PathParam("id") int id) {
return pokemonDAO.isFavorite(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/{login}/{pwd}")
public Trainer pokelogin(@PathParam("login") String login, @PathParam("pwd") String pwd) {
return trainerDAO.authUser(login, pwd);
}
@DELETE
@Path("poke/delete/{id}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public boolean delete(@PathParam("id")int id) {
return pokemonDAO.deletePokemon(id);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("poke/insert")
public boolean pokeInsert(String content) {
Gson gson = new Gson();
Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class);
return pokemonDAO.insertPokemon(pokemon);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("poke/update")
public boolean pokeUpdate(String content) {
Gson gson = new Gson();
Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class);
return pokemonDAO.updatePokemon(pokemon);
}
/**
* PUT method for updating or creating an instance of GenericResource
* @param content representation for the resource
*/
@PUT
@Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
这是我的 DAO 的代码:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dbconn.ConnectionFactory;
import model.Pokemon;
public class PokemonDAO {
public boolean insertPokemon(Pokemon pokemon) {
thử {
Connection conn = ConnectionFactory.getConnection();
String insertQuery = "INSERT INTO `pokedex`.`pokemon` (`name`,`species`,`weight`,`height`,`image`,`isFavorite`,`trainerId`) "
+ "VALUES (?, ?, ?, ?, ?, 0, ?)";
PreparedStatement stmt = conn.prepareStatement(insertQuery);
stmt.setString(1, pokemon.getName());
stmt.setString(2, pokemon.getSpecies());
stmt.setString(3, pokemon.getWeight());
stmt.setString(4, pokemon.getHeight());
stmt.setString(5, pokemon.getImage());
stmt.setInt(6, pokemon.getTrainerId());
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
trả về false;
}
trả về giá trị đúng;
}
public boolean deletePokemon(int id) {
thử {
Connection conn = ConnectionFactory.getConnection();
String deleteQuery = "DELETE FROM `pokedex`.`pokemon` WHERE id = ?;";
PreparedStatement stmt = conn.prepareStatement(deleteQuery);
stmt.setInt(1
, id);
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
trả về false;
}
trả về giá trị đúng;
}
public ArrayList listPokemon() {
ArrayList pokemonList = new ArrayList();
thử {
Connection conn = ConnectionFactory.getConnection();
//String listQuery = "SELECT * fROM `pokedex`.`pokemon`";
String listQuery = "SELECT `pokemon`.`id`,\n" +
" `pokemon`.`name`,\n" +
" `pokemon`.`species`,\n" +
" `pokemon`.`weight`,\n" +
" `pokemon`.`height`,\n" +
" `pokemon`.`image`,\n" +
" `pokemon`.`isFavorite`,\n" +
" `pokemon`.`trainerId`\n" +
"FROM `pokedex`.`pokemon`;";
PreparedStatement stmt = conn.prepareStatement(listQuery);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
Pokemon pokemon = new Pokemon();
pokemon.setId(rs.getInt(1));
pokemon.setName(rs.getString(2));
pokemon.setSpecies(rs.getString(3));
pokemon.setWeight(rs.getString(4));
pokemon.setHeight(rs.getString(5));
pokemon.setImage(rs.getString(6));
pokemon.setIsFavorite(rs.getString(7));
pokemon.setTrainerId(rs.getInt(8));
pokemonList.add(pokemon);
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
trả về giá trị null;
}
return pokemonList;
}
public Pokemon fetchPokemon(int id) {
Pokemon pokemon = null;
thử {
Connection conn = ConnectionFactory.getConnection();
String fetchQuery = "SELECT * fROM `pokedex`.`pokemon` WHERE id = ?;";
PreparedStatement stmt = conn.prepareStatement(fetchQuery);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
pokemon = new Pokemon();
pokemon.setId(rs.getInt(1));
pokemon.setName(rs.getString(2));
pokemon.setSpecies(rs.getString(3));
pokemon.setWeight(rs.getString(4));
pokemon.setHeight(rs.getString(5));
pokemon.setImage(rs.getString(6));
pokemon.setIsFavorite(rs.getString(7));
pokemon.setTrainerId(rs.getInt(8));
} khác {
return pokemon;
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
trả về giá trị null;
}
return pokemon;
}
public boolean updatePokemon(Pokemon pokemon) {
thử {
Connection conn = ConnectionFactory.getConnection();
String insertQuery = "UPDATE `pokedex`.`pokemon` SET `name` = ?, `species` = ?, `weight` = ?, "
+ "`height` = ?, `image` = ?, `isFavorite` = ? WHERE `id` = ?;";
PreparedStatement stmt = conn.prepareStatement(insertQuery);
stmt.setString(1, pokemon.getName());
stmt.setString(2, pokemon.getSpecies());
stmt.setString(3, pokemon.getWeight());
stmt.setString(4, pokemon.getHeight());
stmt.setString(5, pokemon.getImage());
stmt.setString(5, pokemon.isFavorite());
stmt.setInt(6, pokemon.getId());
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
trả về false;
}
trả về giá trị đúng;
}
public String isFavorite(int id) {
Pokemon pokemon = null;
thử {
Connection conn = ConnectionFactory.getConnection();
String fetchQuery = "SELECT teste fROM `pokedex`.`pokemon` WHERE id = ?;";
PreparedStatement stmt = conn.prepareStatement(fetchQuery);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
pokemon = new Pokemon();
pokemon.setIsFavorite(rs.getString(1));
} khác {
return pokemon.isFavorite();
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
return pokemon.isFavorite();
}
return pokemon.isFavorite();
}
}
我没有制作代码来请求它。我正在 Netbeans 上使用“测试 Restful Web 服务”工具运行测试。这可能是问题的原因吗?
这是我在 Netbeans 上运行测试的工具: "Test Restful Web Services" tool
1 Câu trả lời
可能 Netbeans 正在尝试将我的请求作为 get 发送。我对 Postman 和我在网上获得的代码进行了测试,只是做了一些更改。两者都运作良好。 :
This is the result I got from Postman
这是在 Netbeans 上运行的代码:
package acessorest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
*
* @author marcelosiedler
*/
public class HttpExemple {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpExemple http = new HttpExemple();
Gson gson = new Gson();
Pokemon pokemon = new Pokemon();
java.lang.reflect.Type pokemonType = new TypeToken() {
}.getType();
String chamadaWS = "http://localhost:8081/PokedexWS/webresources/pokews/poke/delete/4";
String return = http.sendGet(chamadaWS, "DELETE");
//pokemon = gson.fromJson(json, pokemonType);
System.out.println(return);
}
// HTTP GET request
private String sendGet(String url, String method) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod(method);
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
ghim theo();
//print result
System.out.println(response.toString());
return response.toString();
}
// HTTP POST request
private void sendPost(String url, String parameters, String method) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
ghim theo();
//print result
System.out.println(response.toString());
}
}
And this is the return I got from Netbeans console
非常感谢大家的帮助!
关于java - HTTP 状态 405 – @DELETE 方法不允许使用该方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50948311/
Tôi muốn hiểu phương thức methods() của Ruby hoạt động như thế nào. Tôi đã thử tìm kiếm trên Google bằng "phương pháp ruby", nhưng đó không phải là những gì tôi cần. Tôi cũng đã xem ruby-doc.org nhưng không tìm thấy phương pháp này.
Phương thức Test thực hiện tìm kiếm biểu thức chính quy trên chuỗi đã chỉ định và trả về giá trị Boolean cho biết liệu có tìm thấy kết quả khớp hay không. object.Test(string) Tham số object Bắt buộc. Luôn luôn là một
Phương pháp Thay thế thay thế văn bản được tìm thấy trong tìm kiếm biểu thức chính quy. object.Replace(string1, string2) Tham số object Bắt buộc. Luôn luôn là tên của đối tượng RegExp.
Phương thức Raise tạo ra một đối tượng lỗi thời gian chạy. Raise(số, nguồn, mô tả, tệp trợ giúp, ngữ cảnh trợ giúp) Đối tượng tham số phải là
Phương thức Execute thực hiện tìm kiếm biểu thức chính quy trên chuỗi đã chỉ định. object.Execute(string) Tham số object Bắt buộc. Luôn luôn là tên của đối tượng RegExp. sợi dây
Phương thức Clear xóa tất cả các thiết lập thuộc tính của đối tượng Err. object. Đối tượng xóa phải là tên của đối tượng Err. Mô tả Sau khi xử lý lỗi, sử dụng Clear để xóa rõ ràng đối tượng Err. cái này
Phương pháp CopyFile sao chép một hoặc nhiều tệp từ vị trí này sang vị trí khác. object.CopyFile nguồn, đích[, ghi đè] Đối tượng tham số bắt buộc
Phương pháp Copy sao chép một tệp hoặc thư mục được chỉ định từ vị trí này sang vị trí khác. object.Copy destination[, ghi đè] Tham số object Bắt buộc. Tệp hoặc F dự kiến
Phương thức Close đóng tệp TextStream đã mở. Đối tượng object.Close phải là tên của đối tượng TextStream. Ví dụ sau minh họa cách sử dụng phương thức Close.
Phương thức BuildPath thêm tên vào đường dẫn hiện có. object.BuildPath(path, name) Tham số object Bắt buộc. Phải là tên của đối tượng FileSystemObject
Phương thức GetFolder trả về một đối tượng Folder tương ứng với một thư mục trong đường dẫn đã chỉ định. object.GetFolder(folderspec) Tham số object Bắt buộc. Nên là FileSy
Phương thức GetFileName trả về tệp hoặc thư mục cuối cùng trong đường dẫn đã chỉ định (không phải phần đường dẫn ổ đĩa đã chỉ định). object.GetFileName(pathspec) Tham số object Bắt buộc. Nên là
Phương thức GetFile trả về một đối tượng File tương ứng với một file trong đường dẫn đã chỉ định. object.GetFile(filespec) Tham số object Bắt buộc. FileSystemObject mong đợi
Phương thức GetExtensionName trả về một chuỗi chứa phần mở rộng của thành phần cuối cùng của đường dẫn. object.GetExtensionName(path) Tham số object Bắt buộc. trả lời
Phương thức GetDriveName trả về một chuỗi chứa tên ổ đĩa trong đường dẫn đã chỉ định. object.GetDriveName(path) Tham số object Bắt buộc. Nên là FileSystemObject
Phương thức GetDrive trả về một đối tượng Drive tương ứng với ổ đĩa trong đường dẫn đã chỉ định. object.GetDrive tham số drivespec đối tượng Bắt buộc. Nên là FileSystemO
Phương thức GetBaseName trả về một chuỗi chứa tên cơ sở (không có phần mở rộng) của tệp hoặc thư mục trong thông số đường dẫn được cung cấp. object.GetBaseName(path) Tham số object Bắt buộc
Phương thức GetAbsolutePathName trả về đường dẫn đầy đủ và rõ ràng từ đường dẫn được chỉ định. object.GetAbsolutePathName(pathspec) Đối tượng tham số
Phương thức FolderExists trả về True nếu thư mục được chỉ định tồn tại; nếu không, nó trả về False. object.FolderExists(folderspec) Tham số object Bắt buộc
Phương thức FileExists trả về True nếu tệp được chỉ định tồn tại; nếu không, nó trả về False. object.FileExists(filespec) Tham số object Bắt buộc. Nên là FileS
Tôi là một lập trình viên xuất sắc, rất giỏi!