Java HTTP Get httpGet(String urlStr)

Here you can find the source of httpGet(String urlStr)

Description

http Get

License

Apache License

Declaration

public static String httpGet(String urlStr) throws Exception 

Method Source Code


//package com.java2s;
/*//from   ww  w.jav a2s.com
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String httpGet(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.connect();
        return getHttpResponse(conn, 200);
    }

    private static String getHttpResponse(HttpURLConnection conn, int expectedReturnCode) throws IOException {
        System.out.println("response code:" + conn.getResponseMessage());
        if (conn.getResponseCode() != expectedReturnCode) {
            System.out.println("Custom Error:" + conn.getResponseCode());
            throw new IOException(conn.getResponseMessage());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        return sb.toString();
    }
}

Related

  1. httpGet(String httpUrl)
  2. httpGet(String url)
  3. httpGet(String url, boolean logStdout)
  4. httpGet(String url, StringBuffer response)
  5. httpGet(String urlStr)
  6. httpGet(String urlToRead)
  7. httpGetString(String url)
  8. readUrl(final String strUrl)
  9. readURL(final String textURL)