如何在OK-HTTP标头中添加非ASCII字符串?

时间:2016-06-06 08:57:13

标签: java android base64 okhttp

我需要在请求的标头中添加Base64字符串。现在我的base64字符串是mobileNum + pin。这就是我生成编码字符串的方式:

public static String getAuthentication(String userName,String spin)
{
    String userCredentials = userName+":"+spin;
    String base64=null;
    try
    {
        byte[] data = userCredentials.getBytes("UTF-8");
        base64 = Base64.encodeToString(data, Base64.DEFAULT);
    }
    catch (UnsupportedEncodingException e){}

    String basicAuth = "Basic "+ new String(base64);

    return basicAuth;
}

而且,现在当我尝试从Ok-HTTP发出请求时,

Request request = new Request.Builder()
            .url(url+sp.getString("MOB",""))
            .get()
            .addHeader("xkey", ""+Auth.getApiKey())
            .addHeader("authorization",""+Auth.getAuthentication(sp.getString("MOB",""),sp.getString("SPIN","")))
            .addHeader("cache-control", "no-cache")
            .build();

它抛出异常,说:

 java.lang.IllegalArgumentException: Unexpected char 0x0a at 30 in authorization value: Basic OTE4MTExODExNjYwOjEyMzQ=

                  at okhttp3.Headers$Builder.checkNameAndValue(Headers.java:320)
                  at okhttp3.Headers$Builder.add(Headers.java:270)
                  at okhttp3.Request$Builder.addHeader(Request.java:175)
                  at com.shreybank.shrey.activities.RegisterActivity.getCredentials(RegisterActivity.java:244)
                  at com.shreybank.shrey.activities.RegisterActivity.access$900(RegisterActivity.java:38)
                  at com.shreybank.shrey.activities.RegisterActivity$4.onResponse(RegisterActivity.java:229)
                  at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
                  at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                  at java.lang.Thread.run(Thread.java:818)

解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

Basic OTE4MTExODExNjYwOjEyMzQ=
012345678901234567890123456789

你的String的末尾附有一些东西!

0xa = LF (Line Feed)

您可以在自己的堆栈跟踪中看到换行符!

因此您在值的末尾有一个无效的换行符。我看不到任何会添加的代码。不要多次使用addHeader(...),而是直接将值添加到标题中。

好吧,如何正确使用它:

request request = new Request.Builder()
        .url(url+sp.getString("MOB",""))
        .get()
        .addHeader(
            new Headers.Builder().add("xkey", ""+Auth.getApiKey())
           .add("authorization",""+Auth.getAuthentication(sp.getString("MOB",""),sp.getString("SPIN","")))
           .add("cache-control", "no-cache")).build())
        .build();

好的,这段代码是 NOT 测试它只是解释了你应该怎么做:使用新的标题生成器,添加键/值,然后通过调用build() <创建标题/ p>

查看HeaderBuilder,请参阅HeaderBuilder