通过 HTTP 身份验证将凭据传递到服务器并获取响应的完整指南

发布于 2024-08-16 12:43:05 字数 262 浏览 4 评论 0原文

所以我们知道如何进行http get 和post 连接。 http://exampledepot.com/egs/java.net/pkg.html 我们希望将凭据(uname、passwd)传递到任何 Web 服务器以访问 url 或获取响应。 而且我们不能将它作为 post 参数传递。 所以看看这个非常简单的代码,它完成了这一切。

So we know how to do http get and post connections.
http://exampledepot.com/egs/java.net/pkg.html
And we want to pass credentials(uname,passwd) to any web server to access the url or get the response.
And we can't pass it as post parameters.
So have a look @ this very simple code which does it all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深府石板幽径 2024-08-23 12:43:06
 try
    {
        // Creatin the connection
        URL url = new URL("http://yoururl");
        URLConnection conn = url.openConnection();

    //sendin the base64 encoded credentials thru d header
    conn.setRequestProperty(
        "Authorization",
        "Basic "+ BasicAuth.encode(username, password));

    // Get the response
    BufferedReader rd = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));

    //readin d response till d end
    while ((line = rd.readLine()) != null) {
        // Process line...
        Log.v("", line);
    }

    rd.close();
}
catch (Exception e) { }

为了对凭据进行编码,我使用了一个名为“BasicAuth.java”的简单外部类,您可以将其添加到您的项目中。
BasicAuth.java

public class BasicAuth {
 private BasicAuth() {}

    // conversion table
    private static byte[] cvtTable = {
        (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E',
        (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J',
        (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O',
        (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T',
        (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y',
        (byte)'Z',
        (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e',
        (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j',
        (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o',
        (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t',
        (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y',
        (byte)'z',
        (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
        (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
        (byte)'+', (byte)'/'
    };

    /**
     * Encode a name/password pair appropriate to
     * use in an HTTP header for Basic Authentication.
     *    name     the user's name
     *    passwd   the user's password
     *    returns  String   the base64 encoded name:password
     */
    static String encode(String name,
                         String passwd) {
        byte input[] = (name + ":" + passwd).getBytes();
        byte[] output = new byte[((input.length / 3) + 1) * 4];
        int ridx = 0;
        int chunk = 0;

        /**
         * Loop through input with 3-byte stride. For
         * each 'chunk' of 3-bytes, create a 24-bit
         * value, then extract four 6-bit indices.
         * Use these indices to extract the base-64
         * encoding for this 6-bit 'character'
         */
        for (int i = 0; i < input.length; i += 3) {
            int left = input.length - i;

            // have at least three bytes of data left
            if (left > 2) {
                chunk = (input[i] << 16)|
                        (input[i + 1] << 8) |
                         input[i + 2];
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = cvtTable[(chunk&0xFC0)   >> 6];
                output[ridx++] = cvtTable[(chunk&0x3F)];
            } else if (left == 2) {
                // down to 2 bytes. pad with 1 '='
                chunk = (input[i] << 16) |
                        (input[i + 1] << 8);
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = cvtTable[(chunk&0xFC0)   >> 6];
                output[ridx++] = '=';
            } else {
                // down to 1 byte. pad with 2 '='
                chunk = input[i] << 16;
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = '=';
                output[ridx++] = '=';
            }
        }
        return new String(output);
    }

}
 try
    {
        // Creatin the connection
        URL url = new URL("http://yoururl");
        URLConnection conn = url.openConnection();

    //sendin the base64 encoded credentials thru d header
    conn.setRequestProperty(
        "Authorization",
        "Basic "+ BasicAuth.encode(username, password));

    // Get the response
    BufferedReader rd = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));

    //readin d response till d end
    while ((line = rd.readLine()) != null) {
        // Process line...
        Log.v("", line);
    }

    rd.close();
}
catch (Exception e) { }

To encode the credentials I am using a simple external class named "BasicAuth.java" which u can just add in to your project.
BasicAuth.java

public class BasicAuth {
 private BasicAuth() {}

    // conversion table
    private static byte[] cvtTable = {
        (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E',
        (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J',
        (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O',
        (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T',
        (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y',
        (byte)'Z',
        (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e',
        (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j',
        (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o',
        (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t',
        (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y',
        (byte)'z',
        (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
        (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
        (byte)'+', (byte)'/'
    };

    /**
     * Encode a name/password pair appropriate to
     * use in an HTTP header for Basic Authentication.
     *    name     the user's name
     *    passwd   the user's password
     *    returns  String   the base64 encoded name:password
     */
    static String encode(String name,
                         String passwd) {
        byte input[] = (name + ":" + passwd).getBytes();
        byte[] output = new byte[((input.length / 3) + 1) * 4];
        int ridx = 0;
        int chunk = 0;

        /**
         * Loop through input with 3-byte stride. For
         * each 'chunk' of 3-bytes, create a 24-bit
         * value, then extract four 6-bit indices.
         * Use these indices to extract the base-64
         * encoding for this 6-bit 'character'
         */
        for (int i = 0; i < input.length; i += 3) {
            int left = input.length - i;

            // have at least three bytes of data left
            if (left > 2) {
                chunk = (input[i] << 16)|
                        (input[i + 1] << 8) |
                         input[i + 2];
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = cvtTable[(chunk&0xFC0)   >> 6];
                output[ridx++] = cvtTable[(chunk&0x3F)];
            } else if (left == 2) {
                // down to 2 bytes. pad with 1 '='
                chunk = (input[i] << 16) |
                        (input[i + 1] << 8);
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = cvtTable[(chunk&0xFC0)   >> 6];
                output[ridx++] = '=';
            } else {
                // down to 1 byte. pad with 2 '='
                chunk = input[i] << 16;
                output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
                output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
                output[ridx++] = '=';
                output[ridx++] = '=';
            }
        }
        return new String(output);
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文