Java HTTP Get readUrl(String urlAsString, int timeout)

Here you can find the source of readUrl(String urlAsString, int timeout)

Description

read Url

License

Apache License

Declaration

public static String readUrl(String urlAsString, int timeout)
            throws IOException 

Method Source Code

//package com.java2s;
/**/*from www  . j a  va  2  s .c  o m*/
 * Copyright (C) 2010 Peter Karich <jetwick_@_pannous_._info>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class Main {
    public static String readUrl(String urlAsString, int timeout)
            throws IOException {
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
        hConn.setReadTimeout(timeout);
        hConn.setConnectTimeout(timeout);
        return readInputStream(hConn.getInputStream());
    }

    public static String readInputStream(InputStream is) throws IOException {
        if (is == null)
            throw new IllegalArgumentException("stream mustn't be null!");

        BufferedReader bufReader = new BufferedReader(
                new InputStreamReader(is, "UTF8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufReader.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        bufReader.close();
        return sb.toString();
    }
}

Related

  1. readUrl(final String strUrl)
  2. readURL(final String textURL)
  3. readUrl(HttpURLConnection conn)
  4. readUrl(String url, String token)
  5. readURL(String url, String type)
  6. readURL(URL url)
  7. requestGetMethod(String url, String... params)