Java HTTP Read getInputStreamReader(String httpUrl, int timeout)

Here you can find the source of getInputStreamReader(String httpUrl, int timeout)

Description

Create and open an HTTP connection (GET).

License

Open Source License

Parameter

Parameter Description
httpUrl a parameter
timeout a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static InputStreamReader getInputStreamReader(String httpUrl, int timeout) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
 * Distributed under license by Red Hat, Inc. All rights reserved.
 * This program is made available under the terms of the
 * Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   w w  w  .ja  v a  2  s  . com*/
 *     Exadel, Inc. and Red Hat, Inc. - initial API and implementation
 ******************************************************************************/

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**
     * Create and open an HTTP connection (GET). If the response code is 200 (OK) then returns an input stream reader that reads from this open connection.
     * Otherwise returns null.
     * @param httpUrl
     * @param timeout
     * @return
     * @throws IOException
     */
    public static InputStreamReader getInputStreamReader(String httpUrl, int timeout) throws IOException {
        HttpURLConnection connection = createHttpURLConnection(httpUrl, timeout);
        if (connection != null) {
            return getInputStreamReader(connection);
        }
        return null;
    }

    /**
     * Open the HTTP connection. If the response code is 200 (OK) then returns an input stream reader that reads from this connection.
     * Otherwise returns null.
     * @param httpUrl
     * @param timeout
     * @return
     * @throws IOException
     */
    public static InputStreamReader getInputStreamReader(HttpURLConnection connection) throws IOException {
        return getInputStreamReader(connection, 0);
    }

    private static InputStreamReader getInputStreamReader(HttpURLConnection connection, int redirectAttemptCount)
            throws IOException {
        InputStreamReader responseReader = null;
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // OK
            String contentTypeCharset = null;
            String contentType = connection.getContentType();
            if (contentType != null) {
                Matcher matcher = Pattern.compile("charset=(.+)").matcher(contentType);
                if (matcher.find()) {
                    contentTypeCharset = matcher.group(1);
                }
            }
            InputStream inputStream = connection.getInputStream();
            if (contentTypeCharset != null && contentTypeCharset.length() > 0) {
                responseReader = new InputStreamReader(new BufferedInputStream(inputStream), contentTypeCharset);
            } else {
                responseReader = new InputStreamReader(new BufferedInputStream(inputStream));
            }
        } else if (responseCode >= 300 && responseCode < 400) { // Redirect
            // URLConnection does not redirect automatically if the protocol is different. HTTP -> HTTPS for example.
            // So we have to do it manually.
            String redirectLocation = connection.getHeaderField("location");
            if (redirectLocation != null
                    && !connection.getURL().toString().equalsIgnoreCase(redirectLocation.trim())) { // Ignore responses with empty redirect locations or with the same redirect URL
                redirectAttemptCount++;
                if (redirectAttemptCount > 1) {
                    // Only one redirect is allowed.
                    HttpURLConnection redirectConnection = createHttpURLConnection(redirectLocation,
                            connection.getConnectTimeout());
                    redirectConnection.setIfModifiedSince(connection.getIfModifiedSince());
                    return getInputStreamReader(redirectConnection, redirectAttemptCount);
                }
            }
        }
        return responseReader;
    }

    /**
     * Create an HTTP connection (GET). Returns null if the URL does not use HTTP(S) protocol.
     * @param urlString
     * @param timeout
     * @return
     * @throws IOException
     */
    public static HttpURLConnection createHttpURLConnection(String urlString, int timeout) throws IOException {
        URL url = new URL(urlString);
        URLConnection connetion = url.openConnection();
        HttpURLConnection httpConnection = null;
        if (connetion instanceof HttpURLConnection) {
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.setConnectTimeout(timeout);
        }
        return httpConnection;
    }
}

Related

  1. getInputStream(HttpURLConnection connection)
  2. getInputStream(String myUrl)
  3. getInputStream(String url)
  4. getInputStreamFromURL(String urlname)
  5. getInputStreamFromUrl(String urlString)
  6. getJsonFromUrlWithJsonParameter(String url, String jsonRequest)
  7. getJsonString(String url)
  8. getReader(String url)
  9. getResult(String urlStr, String content)