【问题标题】:"Value <br of type java.lang.String cannot be converted to JSONObject" - Android Studio“java.lang.String 类型的值 <br 无法转换为 JSONObject” - Android Studio
【发布时间】:2021-10-23 23:44:57
【问题描述】:

所以我使用的是 Android Studio (Java),我必须与使用 Apache (xampp) 制作的网站进行通信。我放入了一个 json 对象 3 个变量。其中两个是字符串,另一个是我使用网站上的代码制作的签名 - https://developer.android.com/training/articles/keystore。 错误“Java.lang 类型的值

这是我的代码:

Android 工作室:

KeyStore ks = null;
byte[] signature = null;
try {
    ks = KeyStore.getInstance("AndroidKeyStore");
    ks.load(null);

    KeyStore.Entry entry = ks.getEntry(alias, null);
    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w("DEBUG_EC", "Not an instance of a PrivateKeyEntry");
    }
    Signature s = Signature.getInstance("SHA256withECDSA");
    s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey());
    s.update(data.getBytes());
    signature = s.sign();
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | UnrecoverableEntryException | InvalidKeyException | SignatureException e) {
    e.printStackTrace();
}

JSONObject object2 = new JSONObject();
try {
    object2.put("id", data);
    object2.put("key", key);
    object2.put("signature", signature);
} catch (Exception e) {
    Log.d("ID_DEBUG","Error");
    e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.POST, url, object2, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.d("ID_DEBUG","String Response : "+ response.toString());

        try {
            String resultados = response.getString("result_text");

            if(resultados.equals("missing parameters")){
                Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(),"Sucess!", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            Log.d("ID_DEBUG","Error");
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override public void onErrorResponse(VolleyError error) {
        Log.e("ID_DEBUG", error.toString());
    }
});

queue.add(jsonObjectRequest2);

我决定把部分php代码。 PHP:

<?php
    function json_response($message = null, $code = 200) {
        // clear the old headers
        header_remove();
        // set the actual code
        http_response_code($code);
        // set the header to make sure cache is forced
        header("Cache-Control: no-cache, no-store");
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        // treat this as json
        header('Content-Type: application/json');
        $status = array(
            200 => '200 OK',
            400 => '400 Bad Request',
            422 => 'Unprocessable Entity',
            500 => '500 Internal Server Error'
            );
        // ok, validation error, or failure
        header('Status: '.$status[$code]);
        // return the encoded json
        return json_encode($message,JSON_UNESCAPED_SLASHES);
    }
    
    if (empty($_POST)) {
        $_POST = json_decode(file_get_contents("php://input"), true) ? : [];
    }
    
    (some code ...)
        
    $res = array();
    
    if(empty($_POST['key']) || empty($_POST['signature'])) {
        $res['result_code']=400;
        $res['result_text']='missing parameters';
        echo json_response($res);
    } else {
        $key=$_POST['key'];
        $signature=$_POST['signature'];
        
        $pubkeyid = openssl_pkey_get_public($key);

        // state whether signature is okay or not
        $ok = openssl_verify($data, $signature, $pubkeyid);
        
        if ($ok == 1) {
            if($key != NULL || $signature != NULL){
                
                (some code ...)
                    
                $final_result = array();
                $final_result['result_code']='200';
                $final_result['result_text']='OK';
                
                echo json_response($final_result);
            }
            
        } elseif ($ok == 0) {
            $res['result_code']=400;
            $res['result_text']='invalid signature';
            echo json_response($res);
        } else {
            $res['result_code']=400;
            $res['result_text']='error checking signature';
            echo json_response($res);
        }           
                
        // free the key from memory
        openssl_free_key($pubkeyid);
    }
}

?>

【问题讨论】:

  • 看起来您在期望 JSON 时返回 HTML。
  • 我不明白它是如何或在哪里发生的。我把我的PHP代码,它可能会有所帮助。

标签: java php android


【解决方案1】:

大多数时候&lt;br&gt; 没有结束标签。 &lt;/br&gt;。然而,要完成这项工作,一切都需要一个结束标签。

function json_response($message = null, $code = 200) {
        // clear the old headers
        header_remove();
        // set the actual code
        http_response_code($code);
        // set the header to make sure cache is forced
        header("Cache-Control: no-cache, no-store");
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        // treat this as json
        header('Content-Type: application/json');
        $status = array(
            200 => '200 OK',
            400 => '400 Bad Request',
            422 => 'Unprocessable Entity',
            500 => '500 Internal Server Error'
            );
        // ok, validation error, or failure
        header('Status: '.$status[$code]);
    // Remove BR elements
    $message = str_replace("<BR>", "", $message); // this is what I changed
    // Remove closing BR just in case they did close it
    $message = str_replace("</BR>", "", $message);
        // return the encoded json
        return json_encode($message,JSON_UNESCAPED_SLASHES);
    }

【讨论】:

  • 感谢您的回复。你在说 "{" 和 "}" 吗?因为我仔细检查了三遍,似乎没有任何遗漏。
  • 不,它编辑了我放的东西,可能是因为它是一个 html 标签。 BR 以 结尾。您需要一个带有 BR 和 > 的结束标记
  • 啊我想我明白了,但我的代码中没有任何 BR,这个页面只有 php
  • 它在您正在读取的 HTML 代码中,不在您的代码中,有一个 BR 标签。在 HTML 中,您不需要关闭 BR 标记。但是,您的代码需要关闭所有标签才能读取它。我会给你一个示例代码来告诉你怎么做。
  • 谢谢你,我现在明白你在说什么了。我尝试了您的代码,但错误保持不变。也许问题出在验证签名的代码中?
【解决方案2】:

我找到了解决方案,问题确实是因为密钥和签名的格式。

Android 工作室:

KeyStore ks = null;
byte[] signature = null;
try {
    ks = KeyStore.getInstance("AndroidKeyStore");
    ks.load(null);

    KeyStore.Entry entry = ks.getEntry(alias, null);
    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w("DEBUG_EC", "Not an instance of a PrivateKeyEntry");
    }
    Signature s = Signature.getInstance("SHA256withECDSA");
    s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey());
    s.update(data.getBytes());
    signature = s.sign();
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | UnrecoverableEntryException | InvalidKeyException | SignatureException e) {
    e.printStackTrace();
}

JSONObject object2 = new JSONObject();
try {
    object2.put("id", data);
    object2.put("key", key);
    object2.put("signature", Base64.getEncoder().encodeToString(signature));
} catch (Exception e) {
    Log.d("ID_DEBUG","Error");
    e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.POST, url, object2, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.d("ID_DEBUG","String Response : "+ response.toString());

        try {
            String resultados = response.getString("result_text");

            if(resultados.equals("missing parameters")){
                Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(),"Sucess!", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            Log.d("ID_DEBUG","Error");
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override public void onErrorResponse(VolleyError error) {
        Log.e("ID_DEBUG", error.toString());
    }
});

queue.add(jsonObjectRequest2);

PHP:

<?php
    function json_response($message = null, $code = 200) {
        // clear the old headers
        header_remove();
        // set the actual code
        http_response_code($code);
        // set the header to make sure cache is forced
        header("Cache-Control: no-cache, no-store");
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        // treat this as json
        header('Content-Type: application/json');
        $status = array(
            200 => '200 OK',
            400 => '400 Bad Request',
            422 => 'Unprocessable Entity',
            500 => '500 Internal Server Error'
            );
        // ok, validation error, or failure
        header('Status: '.$status[$code]);
        // return the encoded json
        return json_encode($message,JSON_UNESCAPED_SLASHES);
    }
    
    if (empty($_POST)) {
        $_POST = json_decode(file_get_contents("php://input"), true) ? : [];
    }
    
    (some code ...)
        
    $res = array();
    
    if(empty($_POST['key']) || empty($_POST['signature'])) {
        $res['result_code']=400;
        $res['result_text']='missing parameters';
        echo json_response($res);
    } else {
        $key=$_POST['key'];
        $signature=$_POST['signature'];
        
    $key = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($chave, 64, "\n") . '-----END PUBLIC KEY-----';
    $key = openssl_pkey_get_public($key);
    if ($key == false) {
        $res['result_code']=400;
        $res['result_text']='key error';
        echo json_response($res);
    }
        
        // state whether signature is okay or not
        $ok = openssl_verify($data, base64_decode($signature), $key, OPENSSL_ALGO_SHA256);      
        if ($ok == 1) {
            if($key != NULL || $signature != NULL){
                
                (some code ...)
                    
                $final_result = array();
                $final_result['result_code']='200';
                $final_result['result_text']='OK';           
                echo json_response($final_result);
            }
            
        } elseif ($ok == 0) {
            $res['result_code']=400;
            $res['result_text']='invalid signature';
            echo json_response($res);
        } else {
            $res['result_code']=400;
            $res['result_text']='error checking signature';
            echo json_response($res);
        }           
                
        // free the key from memory
        openssl_free_key($pubkeyid);
    }
}

?>

感谢所有试图提供帮助的人!

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2013-08-02
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多