Java HTTP Response Code getResponseCode(String urlString)

Here you can find the source of getResponseCode(String urlString)

Description

get Response Code

License

Open Source License

Declaration

public static int getResponseCode(String urlString) 

Method Source Code


//package com.java2s;
/*/*  w  ww.j a v a  2 s  .c o m*/
 * This file is part of CraftCommons.
 *
 * Copyright (c) 2011 CraftFire <http://www.craftfire.com/>
 * CraftCommons is licensed under the GNU Lesser General Public License.
 *
 * CraftCommons is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CraftCommons is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static int getResponseCode(String urlString) {
        try {
            return getResponseCode(new URL(urlString));
        } catch (MalformedURLException e) {
            return 0;
        }
    }

    public static int getResponseCode(URL url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
            connection.connect();
            return connection.getResponseCode();
        } catch (IOException e) {
            return 0;
        }
    }
}

Related

  1. getResponseCode(String URL)
  2. getResponseCode(String urlS)
  3. getResponseCode(String urlString)
  4. getResponseCode(String urlString)
  5. getResponseCode(URL url)
  6. getResponseCode(URLConnection connection)