Tenho este REST
@RequestMapping(value = “/buscaEnderecoCep/{cep}”, method = RequestMethod.GET, produces = { “application/json” })
public ResponseEntity buscaEnderecoCep(@PathVariable String cep) {
try {
return new ResponseEntity(viewEnderecoCepServico.buscaEnderecoCep(cep), HttpStatus.OK);
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
}
Quando chamo pela URL pelo navegador assim: http://localhost:8080/nota-fiscal_servico/buscaEnderecoCep/30860100, funciona, trocando no metodo java, de POST para GET.
No Javascript
$("input.cep").blur(function() {buscarCep();});
function buscarCep() {
$.ajax({
type : "POST",
url : "buscaEnderecoCep",
contentType : "application/json; charset=utf-8",
dataType : "json",
async : true,
data : '{cep:"' + document.getElementById("cep").value + '"}',
success : function(data) {
alert(data.d);
}
});
Como deu erro 404, ele não mostra o resultado.
O que pode ser ?
seu serviço pede um GET no Spring e no seu javascript você esta passando um POST , já tentou trocar ?
Já.
Fiz tanto com GET e POST.
Com GET o Erro é 400, conforme imagem
tenta entrar com o CEP sem formato ex: 30860100 .
por que as url estao diferente ? tem um endereço a mais na primeira .
A primeira é feita automaticamente, acho que pelo javascript, conforme imagem, abaixo.
function buscarCep() {
$.ajax({
type : "POST",
url : "buscaEnderecoCep",
contentType : "application/json; charset=utf-8",
dataType : "json",
async : true,
data : '{cep:"' + document.getElementById("cep").value + '"}',
success : function(data) {
alert(data.d);
}
});
No console do eclipse ele mostra este erro:
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
Retirando o {} que tem em data não resolve?
Consegui, mudei o javascript
function buscarCep() {
var er = /[/.-]/gi;
var cep = document.getElementById("cep").value;
cep = cep.replace(er, "");
$.ajax({
type : "GET",
url : "/nota-fiscal_servico/buscaEnderecoCep/"
+ cep,
contentType : "application/json; charset=utf-8",
dataType : "json",
async : true,
success : function(url) {
alert(url.bairro);
}
});
}