⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpposter.java

📁 J2ME MIDP_Example_Applications
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            int requestLength = request.length();
            for (int i = 0; i < requestLength; ++i)
            {
                out.write(request.charAt(i));
            }
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                    // already closing, just ignore
                }
            }
        }
    }


    private String readResponse(HttpConnection conn)
        throws IOException
    {
        InputStream in = null;
        String responseStr = null;
        try
        {
            // Opening the InputStream will open the connection
            // and read the HTTP headers. They are stored until
            // requested.
            in = conn.openInputStream();

            // Get the length and process the data
            StringBuffer responseBuf;
            long length = conn.getLength();
            if (length > 0)
            {
                responseBuf = new StringBuffer((int) length);
            }
            else
            {
                // default length
                responseBuf = new StringBuffer();
            }

            int ch;
            while ((ch = in.read()) != -1)
            {
                responseBuf.append((char) ch);
            }
            responseStr = responseBuf.toString();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    // already closing, just ignore
                }
            }
        }
        return responseStr;
    }


    // This is just for tidying up - the instance is useless after it has
    // been called
    void abort()
    {
        aborting = true;
        synchronized (this)
        {
            // wake up our posting thread and kill it
            notify();
        }
    }


    private String getCredentials(String file, String method, String challenge)
        throws IOException
    {
        String realm = getAuthenticationRealm(challenge);
        if (!authenticationAccepted)
        {
            PromptDialog promptDialog = promptForCredentials(realm);
            if (promptDialog.getUsername() == null)
            {
                throw new IOException("Must give username & password");
            }
            username = promptDialog.getUsername();
            password = promptDialog.getPassword();
        }
        if (authorizationType == BASIC)
        {
            return HttpUtils.base64Encode(username + ":" + password);
        }
        else
        {
            // This is common for Digest and Custom authentication
            return doDigest(file, method, challenge, username, password);
        }
    }


    private String getAuthenticationRealm(String challenge)
        throws IOException
    {
        if (challenge == null)
        {
            throw new IOException("Missing authentication challenge");
        }
        challenge = challenge.trim();
        if (challenge.startsWith("Basic"))
        {
            authorizationType = BASIC;
            int length = challenge.length();
            // we don't check for extra double quotes...
            if ((length < 8) ||
                (!challenge.substring(5, 13).equals(" realm=\"")) ||
                (challenge.charAt(length - 1) != '\"'))
            {
                throw new IOException("Authentication realm syntax error");
            }
            return challenge.substring(13, length - 1);
        }
        else if (challenge.startsWith("Digest"))
        {
            authorizationType = DIGEST;
            challenge = challenge.substring(6, challenge.length()).trim();
            Tokenizer tokenizer = new Tokenizer(challenge, ',');
            while (tokenizer.hasMoreElements())
            {
                String token = ((String) tokenizer.nextElement()).trim();
                if (token.toLowerCase().startsWith("realm"))
                {
                    return token.substring(7, token.length() - 1);
                }
            }
            throw new IOException("Malformed Digest challenge");
        }
        else if (challenge.startsWith("X-Digest"))
        {
            authorizationType = CUSTOM;
            challenge = challenge.substring(8, challenge.length()).trim();
            Tokenizer tokenizer = new Tokenizer(challenge, ',');
            while (tokenizer.hasMoreElements())
            {
                String token = ((String) tokenizer.nextElement()).trim();
                if (token.toLowerCase().startsWith("realm"))
                {
                    return token.substring(7, token.length() - 1);
                }
            }
            throw new IOException("Malformed Digest challenge");
        }
        else
        {
            throw new IOException("Authentication scheme unknown");
        }
    }


    private String doDigest(String file, String method, String challenge,
                            String username, String password)
    {
        // extracts the challenge
        if (challenge.startsWith("X-Digest"))
        {
            challenge = challenge.substring(8, challenge.length()).trim();
        }
        else
        {
            challenge = challenge.substring(6, challenge.length()).trim();
        }
        StringBuffer auth = new StringBuffer("");
        try
        {
            // Now we parse the compononents of the challenge
            Tokenizer tokenizer = new Tokenizer(challenge, ',');
            String opaque = null;
            String realm = null;
            String nonce = null;
            while (tokenizer.hasMoreElements())
            {
                String token = ((String) tokenizer.nextElement()).trim();
                if (token.toLowerCase().startsWith("nonce"))
                {
                    nonce = token.substring(7, token.length() - 1);
                }
                else if (token.toLowerCase().startsWith("opaque"))
                {
                    opaque = token.substring(8, token.length() - 1);
                }
                else if (token.toLowerCase().startsWith("realm"))
                {
                    realm = token.substring(7, token.length() - 1);
                }
            }
            if (realm == null || nonce == null || opaque == null)
            {
                return "";
            }
            auth.append("username=\"").append(username).append("\", ").append("realm=\"");
            auth.append(realm).append("\", nonce=\"").append(nonce).append("\", opaque=\"");
            auth.append(opaque).append("\", uri=\"").append(file).append("\"");

            // Calculate the digested response as in RFC 2617
            // Calculate A1
            String A1 = username + ":" + realm + ":" + password;
            MD5Digest digest = new MD5Digest();
            int size = digest.getDigestSize();
            byte[] allbytes = A1.getBytes();
            byte[] result = new byte[size];
            digest.update(allbytes, 0, allbytes.length);
            digest.doFinal(result, 0);
            A1 = new String(Hex.encode(result));

            // Calculate A2
            String A2 = method + ":" + file;
            allbytes = A2.getBytes();
            digest.update(allbytes, 0, allbytes.length);
            digest.doFinal(result, 0);
            A2 = new String(Hex.encode(result));

            // Calculate the response
            String response = A1 + ":" + nonce + ":" + A2;
            allbytes = response.getBytes();
            digest.update(allbytes, 0, allbytes.length);
            digest.doFinal(result, 0);
            response = new String(Hex.encode(result));

            auth.append(", response=\"").append(response).append("\"");

            return auth.toString();
        }
        catch (Exception e)
        {
            //If there are problems calculating the digest return an empty string
            return "";
        }

    }


    protected PromptDialog promptForCredentials(String realm)
    {
        // This is a nasty method, as it must suspend the current
        // thread, put up a prompt dialog, get the result, and wake
        // up again
        PromptDialog dialog = new PromptDialog(display, realm);
        dialog.promptForInput();
        // this call blocks us until answered
        return dialog;
    }


    private class HttpRequest
    {
        String type;
        String mimeType;
        String request;
        HttpPosterListener listener;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -