Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 截击POST请求返回空,标题和正文为空_Java_Android_Json_Android Volley_Jsonobjectrequest - Fatal编程技术网

Java 截击POST请求返回空,标题和正文为空

Java 截击POST请求返回空,标题和正文为空,java,android,json,android-volley,jsonobjectrequest,Java,Android,Json,Android Volley,Jsonobjectrequest,我遇到了一个问题,onResponse(jsonobjectresponse)总是返回null 我已经将JSONObject.toString作为请求(POST)中的主体传递,并粘贴到Postman中,它可以正常工作;我从服务器(JSON对象)获得有效响应。我也尝试了一个StringRequest,但我没有任何运气 以下是我的PHP: public function decryptTest2($param) { $key = sodium_hex2bin($param['key'

我遇到了一个问题,onResponse(jsonobjectresponse)总是返回null

我已经将JSONObject.toString作为请求(POST)中的主体传递,并粘贴到Postman中,它可以正常工作;我从服务器(JSON对象)获得有效响应。我也尝试了一个StringRequest,但我没有任何运气

以下是我的PHP:

public function decryptTest2($param) {
        $key = sodium_hex2bin($param['key']);
        $nonce = sodium_hex2bin($param['nonce']);
        $chiper = sodium_hex2bin($param['chiper']);

        header('Content-Type: application/json; charset=utf-8');

        $plaintext = sodium_crypto_secretbox_open($chiper, $nonce, $key);
        if ($plaintext === false) {
            throw new Exception("Bad ciphertext");
            $json['error'] = "Not able to decrypt.";
            echo json_encode($json['error']);
        }

        $json['success'] = array("decryptedText" => $plaintext);
        echo json_encode($json['success']);

    }
爪哇:

public void encryptRequest(字符串输入)抛出JSONException{
Encrypt e1=新加密();
碘酸钠=新的碘酸钠();
最终懒散酸钠=新懒散酸钠(钠,标准字符集,UTF_8);
SecretBox.Lazy secretBoxLazy=(SecretBox.Lazy)懒散钠;
最后一个字节[]nonce=lazysinal.randomBytesBuf(SecretBox.NONCEBYTES);
final Key Key=secretBoxLazy.cryptoSecretBoxKeygen();
最终字符串encryptedText=e1.encrypt(输入、nonce、密钥);
JSONObject postMethod=新的JSONObject();
postMethod.put(“方法”,“解密测试2”);
JSONObject postParams=新的JSONObject();
postParams.put(“key”,key.getAsHexString());
postParams.put(“nonce”,Lazynamina.sodiumBin2Hex(nonce));
postParams.put(“Chipper”,encryptedText);
后方法put(“参数”,后参数);
最终字符串requestBody=postMethod.toString();
//{“方法”:“decryptTest2”,“参数”:{“密钥”:“E9C0828178CEC39A8AD713F12E36203AA31C8F48855B6AE5B0C0033D592CE9075”,“暂时”:“94B683D94504D86D3FA654652545CAD3AA3F48636440ABD91”,“芯片工”:“8ED8B092269A0CABE6F8F4D5C851B5E9892956EF7E”}
//System.out.println(“json:+requestBody”);
字符串URL=”http://api.domain.com/index.php";
JsonObjectRequest req=新的JsonObjectRequest(Request.Method.POST、URL、postMethod、,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
System.out.println(“json响应:+response”);
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(getApplicationContext(),error.getMessage(),
Toast.LENGTH_LONG).show();
System.out.println(“json响应:+error.getMessage());
}
}) {
@凌驾
公共字符串getBodyContentType(){
返回“application/json;charset=utf-8”;
}
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map params=新的HashMap();
参数put(“内容类型”,“应用程序/json;字符集=utf-8”);
返回参数;
}
@凌驾
公共字节[]getBody(){
试一试{
return requestBody==null?null:requestBody.getBytes(“utf-8”);
}捕获(不支持的编码异常uee){
wtf(“尝试使用%s获取%s的字节时不支持编码”,
请求主体,“utf-8”);
返回null;
}
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应){
弦乐;
JSONObject JSONObject=null;
if(响应!=null){
试一试{
responseString=新字符串(response.data,HttpHeaderParser.parseCharset(response.headers));
jsonObject=新的jsonObject(responseString);
}捕获(例外e){
e、 printStackTrace();
}
}
返回Response.success(jsonObject,HttpHeaderParser.parseCacheHeaders(Response));
}
};
请求setRetryPolicy(新的DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT\u最大重试次数,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
添加(req);
}

我做错了什么?

好吧,在花了好几个小时试图弄清楚我做错了什么之后,似乎“JsonObjectRequest”不是我想要的。虽然根据,

JSONObject请求—用于在给定URL处检索JSONObject响应主体的请求,允许将可选JSONObject作为请求主体的一部分传入

我最初的想法是:我在body()中发送(发布)一个JSONObject,并从服务器接收一个JSONObject响应,那么,为什么不走这条路线呢?错。我尝试将JSONObject作为参数传递,也尝试重写body()方法,但在Android中我一直收到“null”响应,而Postman工作时没有任何问题

我的解决方案:StringRequest。我还手动创建了主体字符串,而不是创建JSONObject:

public void encryptRequest(String input) {

    Encrypt sodium = new Encrypt();

    final byte[] nonce = sodium.randomNonce();
    final Key key = sodium.randomKey();

    final String encryptedText = sodium.encrypt(input, nonce, key);

    final String jSonString = "{\"method\":\"decryptTest2\", \"params\":{\"cipher\":\"" +
            encryptedText + "\", \"nonce\":\"" + sodium.convertNonce(nonce) +
            "\", \"key\":\"" + sodium.convertKey(key) + "\"}}";

    StringRequest stringRequest = new StringRequest(Request.Method.POST, sodium.getURL(),
            new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jsonObject = new JSONObject(response);

                if (jsonObject.names().get(0).equals("success")) {

                    System.out.println("Decrypted Text: " + jsonObject.getJSONObject("success").getString("decryptedText"));

                }

                else {

                    System.out.println("Error decrypting: " + jsonObject.getJSONObject("error").getString("decryptedText"));

                }


            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("LOG_VOLLEY", e.getMessage());
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("LOG_VOLLEY", error.getMessage());
        }
    }) {
        @Override
        public byte[] getBody() throws AuthFailureError {

            try {
                return jSonString == null ? null : jSonString.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", jSonString, "utf-8");
                return null;
            }
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }
    };

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(stringRequest);

}
public void加密请求(字符串输入){
加密钠=新加密();
最后一个字节[]nonce=钠。随机数();
最终键=钠。随机键();
最终字符串encryptedText=Na钠.encrypt(输入、当前、密钥);
最后一个字符串jSonString=“{\”方法\“:\”解密测试2\“,\”参数\“:{\”密码\“:\”+
encryptedText+“\”,“nonce\”:“\”+钠.转换nonce(nonce)+
“\”,“\”键“:\”+钠转换键(键)+“\”}”;
StringRequest StringRequest=新的StringRequest(Request.Method.POST,naude.getURL(),
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject JSONObject=新JSONObject(响应);
if(jsonObject.names().get(0.equals)(“success”)){
System.out.println(“解密文本:+jsonObject.getJSONObject(“成功”).getString(“解密文本”));
}
否则{
System.out.println(“解密错误:”+jsonObject.getJSONObject(“错误”).getString(“解密文本”));
}
}捕获(JSONException e){
e、 printStackTrace();
public void encryptRequest(String input) {

    Encrypt sodium = new Encrypt();

    final byte[] nonce = sodium.randomNonce();
    final Key key = sodium.randomKey();

    final String encryptedText = sodium.encrypt(input, nonce, key);

    final String jSonString = "{\"method\":\"decryptTest2\", \"params\":{\"cipher\":\"" +
            encryptedText + "\", \"nonce\":\"" + sodium.convertNonce(nonce) +
            "\", \"key\":\"" + sodium.convertKey(key) + "\"}}";

    StringRequest stringRequest = new StringRequest(Request.Method.POST, sodium.getURL(),
            new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jsonObject = new JSONObject(response);

                if (jsonObject.names().get(0).equals("success")) {

                    System.out.println("Decrypted Text: " + jsonObject.getJSONObject("success").getString("decryptedText"));

                }

                else {

                    System.out.println("Error decrypting: " + jsonObject.getJSONObject("error").getString("decryptedText"));

                }


            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("LOG_VOLLEY", e.getMessage());
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("LOG_VOLLEY", error.getMessage());
        }
    }) {
        @Override
        public byte[] getBody() throws AuthFailureError {

            try {
                return jSonString == null ? null : jSonString.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", jSonString, "utf-8");
                return null;
            }
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }
    };

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(stringRequest);

}