HTTP状态405 – @DELETE方法上不允许使用方法

时间:2018-06-20 12:29:31

标签: java mysql rest web-services

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

    try {
        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();
        return false;
    }

    return true;

}

public boolean deletePokemon(int id) {      

    try {
        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();
        return false;
    }

    return true;    
}


public ArrayList<Pokemon> listPokemon() {
    ArrayList<Pokemon> pokemonList = new ArrayList<Pokemon>();

    try {
        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();
        return null;
    }

    return pokemonList;
}

public Pokemon fetchPokemon(int id) {
    Pokemon pokemon = null;

    try {
        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));
        } else {
            return pokemon;
        }

        rs.close();
                    stmt.close();
        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return pokemon;
}

public boolean updatePokemon(Pokemon pokemon) {

    try {
        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();
        return false;
    }

    return true;
}

    public String isFavorite(int id) {
    Pokemon pokemon = null;

    try {
        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));
        } else {
            return pokemon.isFavorite();
        }

        rs.close();
                    stmt.close();
        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
        return pokemon.isFavorite();
    }

    return pokemon.isFavorite();
}
}

我没有编写代码来请求它。我正在使用“测试Restful Web服务”工具在Netbeans上运行测试。可能是问题的原因吗?

这是我在Netbeans上运行测试的工具: "Test Restful Web Services" tool

1 个答案:

答案 0 :(得分:0)

可能是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<Pokemon>() {
                }.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);
        }
        in.close();

        //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);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

And this is the return I got from Netbeans console

非常感谢大家的帮助!