Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:edu.stanford.epadd.launcher.Main.java

private static boolean isURLAlive(String url) throws IOException {
    try {/*www  .  j a v a 2 s.  c om*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {//ww w. ja  va2  s. c o  m
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

public static String getToken(final String username, final String password) {
    try {/*  w ww.  j a v  a 2  s.c o  m*/
        final HttpURLConnection urlConnection = getConnection("/authorization/token");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        JSONObject request = new JSONObject();
        request.put("username", username);
        request.put("password", password);
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        Log.d("SipgateApi", request.getString("username"));
        wr.write(request.toString());
        wr.flush();
        StringBuilder sb = new StringBuilder();
        int HttpResult = urlConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            Log.d("SipgateApi", "" + sb.toString());
            final JSONObject response = new JSONObject(sb.toString());
            return response.getString("token");
        } else {
            System.out.println(urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.dianping.phoenix.dev.core.tools.generator.stable.GitRepositoryListGenerator.java

private static int curl_code(String url) throws Exception {
    URL reqUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(3000);/*w  w  w  .  j av a 2  s .c o  m*/

    conn.setRequestProperty("Cookie",
            "uid=code51c3bceea328e0.87696853; remember_user_token=BAhbB1sGaXFJIiIkMmEkMTAkQUR2YXNENGNqT2NSaDBvVWRSS2guTwY6BkVU--bd148a50388e51e524e89809afd6d98e69793711; request_method=GET; _gitlab_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTMzY2U3YzM3YjlhZWQ1ODcwNDljNDA0MjFkOTdjZjA4BjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMTNqS1V3V2paUCtCWU0rbVZtTUVraFBpTDR3MGFpZ2FtaExXeWphYjJRSVE9BjsARkkiGXdhcmRlbi51c2VyLnVzZXIua2V5BjsAVFsHWwZpcUkiIiQyYSQxMCRBRHZhc0Q0Y2pPY1JoMG9VZFJLaC5PBjsAVA%3D%3D--af5d6859bcba9e86e72ca6c3b2430400db75dcad");
    return conn.getResponseCode();
}

From source file:com.illusionaryone.FrankerZAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;/*from  w  w w .j  a v  a  2 s  .  co m*/
    HttpURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.printStackTrace(ex);
            }
    }

    return (jsonResult);
}

From source file:mdretrieval.FileFetcher.java

public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException {
    String[] ret = new String[2];

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    String dest = destinationURL;
    URL url = new URL(dest);
    Proxy proxy = null;//from   ww w. ja  v a 2s .co m

    if (ServerConstants.isProxyEnabled) {
        proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(ServerConstants.hostname, ServerConstants.port));
        urlConnection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        urlConnection = (HttpURLConnection) url.openConnection();
    }

    boolean redirect = false;

    int status = urlConnection.getResponseCode();
    if (Master.DEBUG_LEVEL >= Master.LOW)
        System.out.println("RESPONSE-CODE--> " + status);
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {
        String newUrl = urlConnection.getHeaderField("Location");
        dest = newUrl;
        urlConnection.disconnect();
        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println("REDIRECT--> " + newUrl);
        urlConnection = openMaybeProxyConnection(proxy, newUrl);
    }

    try {
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        urlConnection.setDoInput(true);
        //urlConnection.setDoOutput(true);            
        inputStream = urlConnection.getInputStream();
        ret[1] = urlConnection.getHeaderField("Content-Type");
    } catch (IllegalStateException e) {
        if (Master.DEBUG_LEVEL >= Master.LOW)
            System.out.println(" DEBUG: IllegalStateException");
        urlConnection.disconnect();
        HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest);
        conn2.setRequestMethod("GET");
        conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        conn2.setDoInput(true);
        inputStream = conn2.getInputStream();
        ret[1] = conn2.getHeaderField("Content-Type");
    }

    try {
        ret[0] = IOUtils.toString(inputStream);

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type"));
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        urlConnection.disconnect();
    }

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Done reading " + destinationURL);
    return ret;

}

From source file:edu.stanford.muse.launcher.Main.java

private static boolean killRunningServer(String url) throws IOException {
    try {/*w  ww.  j  av  a 2  s.c o  m*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20Muse"; // version num spaces and brackets screw up the URL connection
        System.err.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {// www.j  a va  2  s.c  o  m
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}

From source file:com.sungtech.goodTeacher.action.TeacherInfoAction.java

public static String httpUrlRequest(String requestURL, String json) {
    URL url;/*from   w w  w .  jav a2  s  . com*/
    String response = "";
    HttpURLConnection connection = null;
    InputStream is = null;
    try {
        url = new URL(requestURL);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.getOutputStream().write(json.getBytes());
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        int code = connection.getResponseCode();
        System.out.println("code" + code);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
    return response;
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPutNew(String url, String param, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(PUT :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    //param=param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C").replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+");
    String processedURL = url;//+"?MFAChallenge="+param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D";
    URL myURL = new URL(processedURL);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);/*from  w ww  . j  a v  a 2 s. c o  m*/
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(param);
    wr.flush();
    wr.close();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}