Eu criei um webservice que acessa um banco de dados MySQL, mas não consigo deletar registros, recebo sempre o seguinte retorno:
HTTP Status 405 – Method Not Allowed. The method received in the request-line is known by the origin server but not supported by the target resource.
Quando executo a mesma query no console do banco, o registro é deletado. Vi diversos tutoriais utilizando o método @DELETE da mesma forma, não consigo encontrar a razão.
Esse é o código do meu 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;
@Path("pokews")
public class PokedexWebService {
PokemonDAO pokemonDAO = new PokemonDAO();
TrainerDAO trainerDAO = new TrainerDAO();
@Context
private UriInfo context;
public PokedexWebService() {
}
@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}")
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
@Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
Este é o código do meu 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();
}
}
Este é o código que eu usei para chamar o serviço:
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;
public class HttpExemplo {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpExemplo http = new HttpExemplo();
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/1";
String retorno = http.sendGet(chamadaWS, "DELETE");
//pokemon = gson.fromJson(json, pokemonType);
System.out.println(retorno);
}
// 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("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
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;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}