有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过Java执行http客户端时出现JSONObject文本格式错误

我有一段代码,我正在执行一个http client来获得一个响应

public String exmp(StringBuilder sql, String table){
    authCache = new BasicAuthCache();
    basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    String postJsonstr=null;
    try {
        HttpPost httpPost = new HttpPost(API_URL);

        StringBuilder str = new StringBuilder();
        str.append("{");
        str.append("\"format\":\"csv\",");
        str.append("\"version\":\"1.0\",");
        str.append("\"name\":\""+table+"\",");
        str.append("\"encrypted\":\"none\",");
        str.append("\"queries\":[{");
        str.append("\"name\":\""+table+"\",");
        str.append("\"query\":\"" + sql + "\",");
        str.append("\"type\":\"export\"");
        str.append("}]");
        str.append("}");

        httpPost.addHeader("accept", jsonContentType);
        StringEntity posEnt = new StringEntity(str.toString().trim());
        posEnt.setContentType(jsonContentType);
        httpPost.setEntity(posEnt);

        CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);}

当我执行这段代码时,我得到的错误是:org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

我试着用System.out.println((int)sb.toString().trim().charAt(0));来看看第一个字符是什么,根据一些帖子,它是123的正确代码

在上面的代码中httpclient是类(static CloseableHttpClient httpclient;)的全局变量,并在一个函数中初始化,该函数在上述函数之前使用httpclient=HttpClients.custom().setDefaultCredentialsProvider(credentials).build();main调用

当我在第一个字符处有{时,我无法理解为什么会出现这个错误

更新代码:这是我使用^{更新的代码。我还是会犯同样的错误

public String exmp(StringBuilder sql, String table){
        authCache = new BasicAuthCache();
        basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
        String postJsonstr=null;
        try {
            HttpPost httpPost = new HttpPost(API_URL);

            JSONObject sbjson = new JSONObject();
            sbjson.put("format", "csv");
            sbjson.put("version", "1.0");
            sbjson.put("name", table);
            sbjson.put("encrypted", "none");

            JSONArray array = new JSONArray();
            JSONObject item = new JSONObject();
            item.put("name", table);
            item.put("query", sql);
            item.put("type", "export");
            array.put(item);

            sbjson.put("queries", array);

            httpPost.addHeader("accept", jsonContentType);
            StringEntity postEntity = new StringEntity(sbjson.toString());
            posEnt.setContentType(jsonContentType);
            httpPost.setEntity(posEnt);

            CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);}

共 (0) 个答案