代码之家  ›  专栏  ›  技术社区  ›  Kamil

文件下载程序中的基本访问身份验证问题

  •  11
  • Kamil  · 技术社区  · 16 年前

    String authentication = this._login+":"+this._pass;
    String encoding = Base64.encodeToString(authentication.getBytes(), 0);            
    
    String fileName = "data.zip";
    URL url = new URL("http://10.0.2.2/androidapp/data.zip"); 
    
    HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
    
    ucon.setRequestMethod("GET");
    ucon.setDoOutput(true);
    
    ucon.setRequestProperty ("Authorization", "Basic " + encoding);
    ucon.connect();
    
    /*
     * Define InputStreams to read from the URLConnection.
     */
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    
    /*
     * Read bytes to the Buffer until there is nothing more to read(-1).
     */
    ByteArrayBuffer bab = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        bab.append((byte) current);
    }
    
    bis.close();
    
    /* Convert the Bytes read to a String. */
    FileOutputStream fos = this._context.openFileOutput(fileName, this._context.MODE_WORLD_READABLE);
    fos.write(bab.toByteArray());
    fos.close();
    

    可能是密码中的空白造成的吗?

    1 回复  |  直到 16 年前
        1
  •  30
  •   Heinrich Filter    15 年前

    我可能有点晚了,但我遇到了一个类似的问题。

    String encoding = Base64.encodeToString(authentication.getBytes(), 0);
    

    String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
    

    默认情况下,Android Base64 util在编码字符串的末尾添加一个换行符。这将使HTTP头无效并导致“错误请求”。

    Base64.NO\u WRAP标志告诉util创建不带换行符的编码字符串,从而保持HTTP头的完整性。