sách gpt4 ai đã đi

java - HTTP 状态 405 – @DELETE 方法不允许使用该方法

In lại 作者:行者123 更新时间:2023-11-29 17:26:13 25 4
mua khóa gpt4 Nike

我创建了一个访问 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/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com