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

📄 httpsposter.java

📁 J2ME MIDP_Example_Applications
💻 JAVA
字号:
// Copyright 2003 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
package whiteboard;

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.pki.*;

/**
 *  This class accepts and queues POST and GET requests for a particular URL,
 *  and services them in first-in-first-out order. Using the queue allows it to
 *  be thread-safe without forcing its clients ever to block. It also accept
 *  alternative MIME-types: It Supports Basic Authentication
 */
class HttpsPoster
    implements Runnable
{
    protected String url;
    protected Display display;
    protected volatile boolean aborting = false;
    protected Vector requestQueue = new Vector();
    // store the last valid credentials
    protected String credentials = null;
    protected String username = null, password = null;

    HttpsPoster(Display display, String url)
    {
        this.display = display;
        this.url = url;
        Thread thread = new Thread(this);
        thread.start();
    }


    void sendRequest(String type,
                     String request,
                     HttpPosterListener listener)
        throws IOException
    {
        sendRequest(type, null, request, listener);
    }


    synchronized void sendRequest(String type,
                                  String mimeType,
                                  String request,
                                  HttpPosterListener listener)
        throws IOException
    {
        // Create a new request and add it to the queue
        HttpRequest newRequest = new HttpRequest();
        newRequest.type = type;
        newRequest.request = request;
        newRequest.listener = listener;
        newRequest.mimeType = mimeType;
        requestQueue.addElement(newRequest);
        // wake up sending thread
        notify();
    }


    public void run()
    {
        running :
        while (!aborting)
        {
            HttpRequest request = null;

            synchronized (this)
            {
                while (requestQueue.size() == 0)
                {
                    try
                    {
                        // releases lock
                        wait();
                    }
                    catch (InterruptedException e)
                    {
                        // Ignore this thread is not interrupted in MIDP
                    }

                    if (aborting)
                    {
                        break running;
                    }
                }

                request = (HttpRequest) (requestQueue.elementAt(0));
                requestQueue.removeElementAt(0);
            }

            // sendRequest must have notified us
            doSend(request.type,
                   request.mimeType,
                   request.request,
                   request.listener);
        }
    }



    private void doSend(String type, String mimeType,
                        String requestStr, HttpPosterListener listener)
    {
        HttpsConnection conn = null;
        InputStream in = null;
        String responseStr = null;
        String errorStr = "";
        boolean wasError = false;
        CertificateException exc = null;
        try
        {
            int responseCode;
            do
            {
                conn = (HttpsConnection) Connector.open(url);

                // Set the request method and headers
                conn.setRequestMethod(type);

                // write request
                writeRequest(conn, requestStr, mimeType);

                // read response
                responseStr = readResponse(conn);

                responseCode = conn.getResponseCode();
                switch (responseCode)
                {
                    case HttpConnection.HTTP_OK:
                        break;
                    case HttpConnection.HTTP_UNAUTHORIZED:
                        // missing credentials when server requires
                        // them, or credentials sent but invalid
                        credentials = getCredentials(
                            conn.getHeaderField("WWW-Authenticate"));
                        conn.close();
                        // open again, this time with credentials
                        break;
                    default:
                        throw new IOException(
                          "Unsupported response code: "
                          + responseCode);
                }
            } while (responseCode != HttpConnection.HTTP_OK);

            // support URL rewriting for session handling
            String rewrittenUrl = conn.getHeaderField("X-RewrittenURL");
            if (rewrittenUrl != null)
            {
                // use this new one in future
                url = rewrittenUrl;
            }
        }
        catch (CertificateException e)
        {
            wasError = true;
            errorStr = e.getMessage();
            exc = e;
        }
        catch (IOException e)
        {
            wasError = true;
            errorStr = e.getMessage();
        }
        catch (SecurityException e)
        {
            // user permission was denied
            wasError = true;
            errorStr = e.getMessage();
        }
        finally
        {
            if (conn != null)
            {
                try
                {
                    conn.close();
                }
                catch (IOException e)
                {
                    // already closing, just ignore
                }
            }
        }

        if (wasError)
        {
            if (exc != null)
            {
                listener.handleCertificateError(exc);
            }
            else
            {
                listener.handleHttpError(errorStr);
            }
        }
        else
        {
            listener.receiveHttpResponse(responseStr);
        }
    }


    private void writeRequest(HttpConnection conn,
                              String request,
                              String mimeType)
        throws IOException
    {
        OutputStream out = null;

        try
        {
            conn.setRequestProperty("Content-Length",
                                    Integer.toString(request.length()));
            if (mimeType != null)
            {
                conn.setRequestProperty("Content-Type", mimeType);
            }
            if (credentials != null)
            {
                conn.setRequestProperty("Authorization",
                                        "Basic " + credentials);
            }

            // Getting the output stream may flush the headers
            out = conn.openOutputStream();
            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 challenge)
        throws IOException
    {
        String realm = getAuthenticationRealm(challenge);
        promptForCredentials(realm);
        if (username == null || password == null)
        {
            throw new IOException("Must give username & password");
        }
        // Calculate the credentials
        return HttpUtils.base64Encode(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"))
        {
            throw new IOException(
              "Authentication scheme not \"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);
    }



    private void 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
        username = dialog.getUsername();
        password = dialog.getPassword();
    }


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

⌨️ 快捷键说明

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