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

📄 httpconnect.java

📁 [linux.rar] - 嵌入式linux开发教程
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            this.uploadPolicy
                    .displayDebug(
                            "-------------------------------------------------------------------------",
                            80);
            this.uploadPolicy
                    .displayDebug(
                            "-----------------   HEAD message sent (end) -----------------------------",
                            80);
            this.uploadPolicy
                    .displayDebug(
                            "-------------------------------------------------------------------------",
                            80);
            ;
        }

        int status = connectionHelper.readHttpResponse();
        this.uploadPolicy.displayDebug("HEAD status: " + status, 30);
        String headers = connectionHelper.getResponseHeaders();

        // Let's look for the protocol
        Matcher m = Pattern.compile("^(HTTP/\\d\\.\\d)\\s(.*)\\s.*$",
                Pattern.MULTILINE).matcher(headers);
        if (!m.find()) {
            // Using default value. Already initialized.
            this.uploadPolicy
                    .displayErr("Unexpected HEAD response (can't find the protocol): will use the default one.");
        } else {
            // We will return the found protocol.
            protocol = m.group(1);
            this.uploadPolicy.displayDebug("HEAD protocol: " + protocol, 30);
        }

        // Let's check if we're facing an IIS server. The applet is compatible
        // with IIS, only if allowHttpPersistent is false.
        Pattern pIIS = Pattern.compile("^Server: .*IIS*$", Pattern.MULTILINE);
        Matcher mIIS = pIIS.matcher(headers);
        if (mIIS.find()) {
            try {
                this.uploadPolicy.setProperty(
                        UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT, "false");
                this.uploadPolicy
                        .displayWarn(UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
                                + "' forced to false, for IIS compatibility (in HttpConnect.getProtocol())");
            } catch (JUploadException e) {
                this.uploadPolicy.displayWarn("Can't set property '"
                        + UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
                        + "' to false, in HttpConnect.getProtocol()");
            }
        }

        // if we got a redirection code, we must find the new Location.
        if (status == 301 || status == 302 || status == 303) {
            Pattern pLocation = Pattern.compile("^Location: (.*)$",
                    Pattern.MULTILINE);
            Matcher mLocation = pLocation.matcher(headers);
            if (mLocation.find()) {
                // We found the location where we should go instead of the
                // original postURL
                this.uploadPolicy.displayDebug("Location read: "
                        + mLocation.group(1), 50);
                changePostURL(mLocation.group(1));
            }
        }

        return protocol;
    } // getProtocol()

    /**
     * Retrieve the protocol to be used for the postURL of the current policy.
     * This method issues a HEAD request to the postURL and then examines the
     * protocol version returned in the response.
     * 
     * @return The string, describing the protocol (e.g. "HTTP/1.1")
     * @throws URISyntaxException
     * @throws IOException
     * @throws UnrecoverableKeyException
     * @throws IllegalArgumentException
     * @throws CertificateException
     * @throws KeyStoreException
     * @throws UnknownHostException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws JUploadException
     */
    public String getProtocolOld() throws URISyntaxException,
            KeyManagementException, NoSuchAlgorithmException,
            UnknownHostException, KeyStoreException, CertificateException,
            IllegalArgumentException, UnrecoverableKeyException, IOException,
            JUploadException {

        String protocol = HTTPCONNECT_DEFAULT_PROTOCOL;
        String returnCode = null;
        // bRedirect indicates a return code of 301, 302 or 303.
        boolean bRedirect = false;
        URL url = new URL(this.uploadPolicy.getPostURL());
        this.uploadPolicy
                .displayDebug("Checking protocol with URL: " + url, 30);
        Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
        boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
        boolean useSSL = url.getProtocol().equals("https");
        Socket s = Connect(url, proxy);
        // BufferedReader in = new BufferedReader(new
        // InputStreamReader(s.getInputStream()));
        PushbackInputStream in = new PushbackInputStream(s.getInputStream());
        StringBuffer req = new StringBuffer();

        req.append("HEAD ");
        if (useProxy && (!useSSL)) {
            // with a proxy we need the absolute URL, but only if not
            // using SSL. (with SSL, we first use the proxy CONNECT method,
            // and then a plain request.)
            req.append(url.getProtocol()).append("://").append(url.getHost());
        }
        req.append(url.getPath());

        // We must transmit the postURL as is. There may be some redirection
        // when parameters are missing (eg: Coppermine)
        if (null != url.getQuery() && !"".equals(url.getQuery()))
            req.append("?").append(url.getQuery());

        req.append(" ").append(HTTPCONNECT_DEFAULT_PROTOCOL).append("\r\n");
        req.append("Host: ").append(url.getHost()).append("\r\n");
        req.append("Connection: close\r\n\r\n");
        OutputStream os = s.getOutputStream();
        os.write(req.toString().getBytes());
        os.flush();

        // Let's read the first line, and try to guess the HTTP protocol, and
        // look for 301, 302 or 303 HTTP Return code.
        String firstLine = HTTPInputStreamReader
                .readLine(in, "US-ASCII", false);
        if (null == firstLine) {
            // Using default value. Already initialized.
            // This can occur, for instance, when Kaspersky antivirus is on !
            this.uploadPolicy.displayWarn("EMPTY HEAD response");
        } else {
            Matcher m = Pattern.compile("^(HTTP/\\d\\.\\d)\\s(.*)\\s.*")
                    .matcher(firstLine);
            if (!m.matches()) {
                // Using default value. Already initialized.
                this.uploadPolicy.displayErr("Unexpected HEAD response: '"
                        + firstLine + "'");
            }
            this.uploadPolicy.displayDebug("HEAD response: " + firstLine, 80);

            // We will return the found protocol.
            protocol = m.group(1);

            // Do we have some URL to change ?
            returnCode = m.group(2);
            if (returnCode.equals("301") || returnCode.equals("302")
                    || returnCode.equals("303")) {
                bRedirect = true;
                this.uploadPolicy.displayInfo("Received " + returnCode
                        + " (current postURL: "
                        + this.uploadPolicy.getPostURL() + ")");
            }
        }

        // Let's check if we're facing an IIS server. The applet is compatible
        // with IIS, only if allowHttpPersistent is false.
        String nextLine = HTTPInputStreamReader.readLine(in, "US-ASCII", false);
        Pattern pLocation = Pattern.compile("^Location: (.*)$");
        Matcher mLocation;
        while ((nextLine = HTTPInputStreamReader
                .readLine(in, "US-ASCII", false)).length() > 0) {
            if (nextLine.matches("^Server: .*IIS")) {
                try {
                    this.uploadPolicy.setProperty(
                            UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT, "false");
                    this.uploadPolicy
                            .displayWarn(UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
                                    + "' forced to false, for IIS compatibility (in HttpConnect.getProtocol())");
                } catch (JUploadException e) {
                    this.uploadPolicy.displayWarn("Can't set property '"
                            + UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
                            + "' to false, in HttpConnect.getProtocol()");
                }
                break;
            } else if (bRedirect) {
                mLocation = pLocation.matcher(nextLine);
                if (mLocation.matches()) {
                    // We found the location where we should go instead of the
                    // original postURL
                    this.uploadPolicy.displayDebug("Location read: "
                            + mLocation.group(1), 50);
                    changePostURL(mLocation.group(1));
                }
            }
        }

        // output is now done at the end of the method, as a remark of Brian
        // Moran
        // This corrects a bug when hitting an NGINX proxy server.
        if (!(s instanceof SSLSocket)) {
            s.shutdownOutput();
        }

        // Let's look for the web server kind: the applet works IIS only if
        // allowHttpPersistent is false
        s.close();

        return protocol;
    } // getProtocol()

    /**
     * Reaction of the applet when a 301, 302 et 303 return code is returned.
     * The postURL is changed according to the Location header returned.
     * 
     * @param newLocation This new location may contain the
     *            http://host.name.domain part of the URL ... or not
     */
    private void changePostURL(String newLocation) throws JUploadException {
        String currentPostURL = this.uploadPolicy.getPostURL();
        String newPostURL;
        Pattern pHostName = Pattern.compile("http://([^/]*)/.*");
        Matcher mOldPostURL = Pattern.compile("(.*)\\?(.*)").matcher(
                currentPostURL);

        // If there is an interrogation point in the original postURL, we'll
        // keep the parameters, and just changed the URI part.
        if (mOldPostURL.matches()) {
            newPostURL = newLocation + '?' + mOldPostURL.group(2);
            // Otherwise, we change the whole URL.
        } else {
            newPostURL = newLocation;
        }

        // There are three main cases or newLocation:
        // 1- It's a full URL, with host name...
        // 2- It's a local full path on the same server (begins with /)
        // 3- It's a relative path (for instance, add of a prefix in the
        // filename) (doesn't begin with /)
        Matcher mHostOldPostURL = pHostName.matcher(currentPostURL);
        if (!mHostOldPostURL.matches()) {
            // Oups ! There is a little trouble here !
            throw new JUploadException(
                    "[HttpConnect.changePostURL()] No host found in the old postURL !");
        }

        // Let's analyze the given newLocation for these three cases.
        Matcher mHostNewLocation = pHostName.matcher(newLocation);
        if (mHostNewLocation.matches()) {
            // 1- It's a full URL, with host name. We already got this URL, in
            // the newPostURL initialization.
        } else if (newLocation.startsWith("/")) {
            // 2- It's a local full path on the same server (begins with /)
            newPostURL = "http://" + mHostOldPostURL.group(1) + newPostURL;
        } else {
            // 3- It's a relative path (for instance, add of a prefix in the
            // filename) (doesn't begin with /)
            Matcher mOldPostURLAllButFilename = Pattern
                    .compile("(.*)/([^/]*)$").matcher(currentPostURL);
            if (!mOldPostURLAllButFilename.matches()) {
                // Hum, that won't be easy.
                throw new JUploadException(
                        "[HttpConnect.changePostURL()] Can't find the filename in the URL !");
            }
            newPostURL = mOldPostURLAllButFilename.group(1) + "/" + newPostURL;
        }

        // Let's store this new postURL, and display some info about the change
        this.uploadPolicy.setPostURL(newPostURL);
        this.uploadPolicy.displayInfo("postURL switched from " + currentPostURL
                + " to " + newPostURL);
    }

    /**
     * Creates a new instance.
     * 
     * @param policy The UploadPolicy to be used for logging.
     */
    public HttpConnect(UploadPolicy policy) {
        this.uploadPolicy = policy;
    }
}

⌨️ 快捷键说明

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