首页 > 解决方案 > 可以为请求传递 json 对象获取我正在尝试的内容,但我错过了以下错误

问题描述

可以为请求传递 json 对象获取我正在尝试的内容,但我错过了以下错误

Caused by: java.net.URISyntaxException: Illegal character in query at index 46: https://localhost/Pro-Ing/rest/pedidos/prueba?{%22codigo%22:%22qwdasdas%22,%22id%22:%221%22}

这是javascript方法

function hola(){
var id= prompt('hola');
var id2= prompt('hola');
codigo = {};
codigo['codigo'] = id;
codigo['id'] = id2;
    $.ajax({
        url : "rest/pedidos/prueba",
        contentType : "application/json",
        dataType : "json",
        type : "GET",
        data : JSON.stringify(codigo),
        success : function(data) {
            jqmSimpleMessage('Paso');
        }
error : function(error) {
            if (error.status == 401) {
                desAuth();
            } else {
                jqmSimpleMessage("error -" + error.responseText);
            }
        },
        beforeSend : function(xhr, settings) {
            xhr.setRequestHeader('Authorization', 'Bearer '
                    + getVCookie(getVCookie("userPro")));
        }
    });
}

这是java接收对象的方法

@GET
@Path("/prueba")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response gendup(confirmacion usu,@Context SecurityContext securityContext) {
    registro(securityContext, 0, "");
    confirmacion confirmacion = null;
    Response.ResponseBuilder builder = null;
    return builder.build();
}

标签: javajsonrestpostget

解决方案


Illegal character in query at index 46: https://localhost/Pro-Ing/rest/pedidos/prueba?{%22codigo%22:%22qwdasdas%22,%22id%22:%221%22}

Java中的数组是从零开始的,所以

01234567890123456789012345678901234567890123456
https://localhost/Pro-Ing/rest/pedidos/prueba?{%22codigo%22:%22qwdasdas%22,%22id%22:%221%22
                                              ^

RFC 3986,附录 A描述了查询中允许使用的字符

query         = *( pchar / "/" / "?" )

pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"

unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

所以你在这里遇到的问题是你的java解析器对URI中允许哪些字符是严格的,左大括号{和右大括号}都不是有效的——它们也需要进行百分比编码。

https://localhost/Pro-Ing/rest/pedidos/prueba?%7B%22codigo%22:%22qwdasdas%22,%22id%22:%221%22%7D

此 URI 以及按规范要求编码的括号百分比,应该满足 java 代码。

我猜 JSON.stringify 正在做我们期望的事情:

> JSON.stringify({"codingo":"qwdasdas","id":"1"})
'{"codingo":"qwdasdas","id":"1"}'

根据您提供的信息,对我来说没有任何意义的原因是为什么您会收到一个查询,其中引号正在获得百分比编码,而不是左大括号和右大括号。您的 URI 看起来像是有人决定推出自己的 URI 编码器,并且没有正确处理所有“特殊字符”。

验证这是在您的 java 脚本端而不是在服务器上运行的 java 的问题的一种方法是查看正在生成的 HTTP 请求,并验证用作请求的目标 uri 的值:如果查询在请求中有无效的拼写,那么服务器肯定与问题无关(除了报告它)。


推荐阅读