Android

时间:2015-05-12 10:53:26

标签: java android httprequest

我有以下代码

更新:只有Android应用程序存在问题,它在java应用程序中运行良好

Java(不适用于大标头值)

URL url = new URL("MyUrl"); //<===This could even be http://www.google.com  
HttpURLConnection request = (HttpURLConnection) url.openConnection();

String userCredentials = "username:AAAAABBBBBBBBCCCCSSSSSSSSSDDDDDDDDDDBE4B97CC9E81DB";
String basicAuth = "Basic " +  android.util.Base64.encodeToString(
            userCredentials.getBytes(), android.util.Base64.DEFAULT);
request.setRequestProperty ("Authorization", basicAuth);

request.connect();
InputStream stream = (InputStream) request.getContent();

当我调用getContent()

时,我得到一个ClassNotFoundException
java.lang.ClassNotFoundException: Didn't find class "org.apache.harmony.awt.www.content.text.html__charset_us_ascii" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
ClassLoader.class第514行中的

 protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
    Class<?> clazz = findLoadedClass(className);


    if (clazz == null) {
        ClassNotFoundException suppressed = null;
        try {
            clazz = parent.loadClass(className, false);
        } catch (ClassNotFoundException e) {
            suppressed = e;
        }

        if (clazz == null) {
            try {
                clazz = findClass(className);
            } catch (ClassNotFoundException e) {
                e.addSuppressed(suppressed);
               //className=org.apache.harmony.awt.www.content.text.html__charset_us_ascii
                throw e;  //<===The code crashes here

            }
        }
    }

    return clazz;
}

问题是Authorization标头的大小,即使它不是那么大(88个字符)
如果我将标题的值更改为更小的值,则可以正常工作 我可以以某种方式更改标题的最大尺寸吗?

我已经从其他平台(Windows,Windows Phone,Web)尝试过,它运行正常,问题不在我的服务器上。

jQuery(始终有效)

var usernameAndPasword=["username","AAAAABBBBBBBBCCCCSSSSSSSSSDDDDDDDDDDBE4B97CC9E81DB"].join(":");
var authorizationHeaderValue="Basic "+   window.btoa(usernameAndPasword);

$.ajax({
    url : "http://...",
    type: "GET",
    beforeSend: function (request) {    request.setRequestHeader("Authorization", authorizationHeaderValue); },
    success: function(data, textStatus, jqXHR)  {   alert(data +  "\n" + textStatus ); },
    error: function (jqXHR, textStatus, errorThrown){ alert(jqXHR.responseText +  " \n " + textStatus + " \n"+errorThrown); }
  }); 

C#(始终有效)

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUristring);
 request.Method = "GET";
 request.Headers["Accept-Encoding"] = "gzip, deflate";

 var bytes = Encoding.UTF8.GetBytes("username" + ":" + "AAAAABBBBBBBBCCCCSSSSSSSSSDDDDDDDDDDBE4B97CC9E81DB" );
 var base64 = Convert.ToBase64String(bytes);
 request.Headers["Authorization"] = "Basic " + base64;

 HttpWebResponse webResponse = (HttpWebResponse)request.GetResponseAsync().Result;

1 个答案:

答案 0 :(得分:-3)

当您使用base64编码时,编码字符串的最大长度应为64,如果是MIME,则编码字符串的最大长度应为76。

有关详细信息,请查看this