Search code examples
javaandroidencodingandroid-volleycontent-type

Volley send request without encoding it


I'm trying to send a HTTP request to a wifi controller, with a normal String. My String is API:W/PSS:12345 but when sent via my Android app, the controller recieves API=W%2FPSS%3A12345. I know this happens due to the header value content-type: application/x-www-form-urlencoded.

However, in my request I've overriden the method:

public String getBodyContentType() {
    return "text/html;";
}

to set the content type to plain text, but volley still encodes it before sending it. (Using a REST client on my PC, sends the request to the controller without encoding it)

Is there a way to send my string as plain text without volley encoding it? The controller is low level so I do not want to add any encoding on both sides, just send plain strings.


Solution

  • After digging through the volley source code, I found the culprit to be that a java URLEncoder.encode() method is called, which will encode the string no matter what... I skipped this with a very hack-y way. If any of you have a better way of doing this PLEASE let me know, as this is very ugly:

    @Override
    public String getBodyContentType() {
        //for settings the content=type header, the right way...
        return return "text/html";
    }
    
    @Override
    public byte[] getBody() throws AuthFailureError {
        Map<String, String> params = getParams();
            if (params != null && params.size() > 0) {
                return encodeParameters(params, getParamsEncoding());
            }
        return null; 
    }
    
    //Hax.......
    private byte[] encodeParameters(Map<String, String> params, String paramsEncoding){
        StringBuilder encodedParams = new StringBuilder();
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    encodedParams.append(entry.getKey());
                    //encodedParams.append(':');
                    encodedParams.append(entry.
                    //encodedParams.append('&');
                }
                return encodedParams.toString().getBytes(paramsEncoding);
            } catch (UnsupportedEncodingException uee) {
                throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
            }
    }
    

    The source code of volley is here, you can take a look at how it encodes items: https://android.googlesource.com/platform/frameworks/volley/+/idea133/src/com/android/volley/Request.java