当我尝试设置 header 时出现 Volley 投掷错误

Volley throwing error when I try to set a header

当我向我的 Volley 字符串请求添加自定义 header 时,我收到一条错误消息 Unexpected char 0x0a at 18 in header value

这是我的代码。

stringRequest = new StringRequest(Request.Method.GET, URL, string -> {
            try {
                JSONObject jsonObject = new JSONObject(string);
                Log.d("TAG", jsonObject.toString());
            } catch (Exception e) {

            }
        }, error -> {

        }){
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String>  params = new HashMap<>();
                params.put("MIME Type", "application/x-www-form-urlencoded; charset=UTF-8");
                params.put("compiler", "c");
                params.put("code", code);
                params.put("input", "");
                return params;
            }
        };

我遇到的错误。

2020-10-07 10:52:06.869 32119-32232/com.my.app E/Volley: [2415] NetworkDispatcher.processRequest: Unhandled exception java.lang.IllegalArgumentException: Unexpected char 0x0a at 18 in header value: #include <stdio.h>
    
    int main()
    {
int foo = 0;
    
printf("Hello world");
    
return foo;
    }
    java.lang.IllegalArgumentException: Unexpected char 0x0a at 18 in header value: #include <stdio.h>
    
    int main()
    {
int foo = 0;
    
printf("Hello world");
    
return foo;
    }
        at com.android.okhttp.Headers$Builder.checkNameAndValue(Headers.java:319)
        at com.android.okhttp.Headers$Builder.add(Headers.java:250)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.addRequestProperty(HttpURLConnectionImpl.java:600)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.addRequestProperty(DelegatingHttpsURLConnection.java:187)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.addRequestProperty(HttpsURLConnectionImpl.java:30)
        at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:95)
        at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
        at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
        at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)

0x0A 是 \n 换行符。确保在你的 header 中没有 "\n".

我认为在您的 header 中您有一些台词! 您可以使用 body!

发送代码

解决了它

• 第 1 步:移除 params.put("MIME Type", "application/x-www-form-urlencoded; charset=UTF-8");

• 第 2 步:将 params.put("code", code); 替换为 params.put("code", Base64.encodeToString(code.getBytes(), Base64.NO_WRAP));

更新

• 我已从我的代码中删除了第 2 步,因为它给我带来了问题。所以现在看起来像 params.put("code", code);