【问题标题】:Volley send request without encoding itVolley 发送请求而不对其进行编码
【发布时间】:2016-06-24 12:10:11
【问题描述】:

我正在尝试使用普通字符串向 wifi 控制器发送 HTTP 请求。我的字符串是 API:W/PSS:12345,但是当通过我的 Android 应用程序发送时,控制器会收到 API=W%2FPSS%3A12345。我知道这是由于标题值content-type: application/x-www-form-urlencoded 而发生的。

但是,在我的请求中,我已经覆盖了该方法:

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

将内容类型设置为纯文本,但 volley 在发送之前仍对其进行编码。 (在我的 PC 上使用 REST 客户端,将请求发送到控制器而不对其进行编码)

有没有办法将我的字符串作为纯文本发送而不用凌空编码?控制器是低级的,所以我不想在两边添加任何编码,只需发送纯字符串。

【问题讨论】:

    标签: java android encoding android-volley content-type


    【解决方案1】:

    也覆盖 getHeaders 方法,并在标题中设置您的内容类型,如下所示:

    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/text");
        return headers;
    }
    

    【讨论】:

    • 刚试了一下,volley 还是先编码再发送。澄清一下:现在我有两个内容类型的标题。不仅仅是applcation/text。我需要添加 utf-8 编码或类似的东西吗?
    【解决方案2】:

    在挖掘了 volley 源代码之后,我发现罪魁祸首是调用了一个 java URLEncoder.encode() 方法,无论如何它都会对字符串进行编码......我用一种非常hack-y的方式跳过了这个。如果你们有更好的方法,请告诉我,因为这很丑:

    @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);
            }
    }
    

    volley的源码在这里,你可以看看它是如何对item进行编码的:https://android.googlesource.com/platform/frameworks/volley/+/idea133/src/com/android/volley/Request.java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2019-07-17
      • 2015-07-09
      • 2017-09-18
      相关资源
      最近更新 更多