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:com.crawler.app.run.CrawlSiteController.java

public static Boolean checkWebSite(URL url) {
    HttpURLConnection connection;
    int code = 0;
    try {/*from  w  w  w . jav  a  2 s .  c o  m*/
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        code = connection.getResponseCode();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (code == 200) {
        return true;
    } else {
        return false;
    }

}

From source file:RemoteDeviceDiscovery.java

public static void postDevice(RemoteDevice d) throws Exception {
    String url = "http://bluetoothdatabase.com/datacollection/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "blucat");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = deviceJson(d);

    // Send post request
    con.setDoOutput(true);//from  w ww . j a  va  2s.  c  o  m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

public static String useLuxidWS(String input, String token, String outputFormat, String annotationPlan)
        throws Exception {
    String s = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd="
            + "\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> "
            + "<SOAP-ENV:Body> <ns1:annotateString xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:sessionKey>" + token + "</ns1:sessionKey> <ns1:plan>" + annotationPlan
            + "</ns1:plan> <ns1:data>";

    s += input;// "This is a great providing test";

    s += "</ns1:data> <ns1:consumer>" + outputFormat + "</ns1:consumer> </ns1:annotateString> </SOAP-ENV:Body> "
            + "</SOAP-ENV:Envelope>";

    URL url = new URL("http://193.104.205.28//LuxidWS/services/Annotation");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*  w  w w. ja  v a2s . co  m*/

    conn.getOutputStream().write(s.getBytes());

    StringBuilder res = new StringBuilder();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = conn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        StringEscapeUtils.escapeHtml("");
        while ((line = rd.readLine()) != null) {
            res.append(line);
        }
        rd.close();
    }
    //      res = URLDecoder.decode(res, "UTF-8");
    return StringEscapeUtils.unescapeHtml(res.toString().replace("&amp;lt", "<"));
}

From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 */// w w  w.  j a  v  a 2  s.c om
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the PoliceStations JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * check if an url doesn't return 200 or 3XX code
 * @param urlAsString the url to check/*ww w  .  ja v  a 2 s.c o m*/
 * @return true if the url exists and is valid
 */
public static boolean checkUrl(String urlAsString) {
    if (urlAsString == null) {
        logger.error("can not check null URL");
        return false;
    }
    URL url;
    try {
        url = new URL(urlAsString);
    } catch (MalformedURLException e) {
        logger.error(urlAsString + " is not a valid url, can not check.");
        return false;
    }
    int responseCode;
    String responseMessage = "NO RESPONSE MESSAGE";
    Object content = "NO CONTENT";
    HttpURLConnection huc;
    try {
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        responseCode = huc.getResponseCode();
        content = huc.getContent();
        responseMessage = huc.getResponseMessage();
    } catch (ProtocolException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    } catch (IOException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    }

    if (responseCode == 200 || (responseCode > 300 && responseCode < 400)) {
        logger.info("URL " + urlAsString + " exists");
        return true;
    } else {
        logger.error(urlAsString + " return a " + responseCode + " : " + content + "/" + responseMessage);
        return false;
    }
}

From source file:a122016.rr.com.alertme.QueryUtils.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//*  ww  w  .  jav a2s.  co  m*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the Places JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java

/**
 * Check if a string appear in the html page
 *
 * @param url//from  ww w  .  ja v  a  2s .  co m
 *            URL to test
 * @param token
 *            String that must be in html page
 * @return Cookie that identifies the was or null if the test failed. An
 *         empty string means that no cookie was found in the request, but
 *         the check succeeded.
 */
private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost,
        int httpProxyPort) {
    InputStream is = null;
    String cookie = null;
    try {
        HttpURLConnection connection;
        if (httpProxyHost != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestMethod("GET");

        is = connection.getInputStream();
        // check http status code
        if (connection.getResponseCode() == 200) {
            DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
            StringWriter writer = new StringWriter();
            IOUtils.copy(dis, writer, "UTF-8");
            if (writer.toString().contains(token)) {
                cookie = connection.getHeaderField("Set-Cookie");
                if (cookie == null)
                    cookie = "";
            } else {
                logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token
                        + "'");
                logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000));
            }
        } else {
            logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : "
                    + connection.getResponseMessage());
            if (System.getProperty("http.proxyHost") != null) {
                logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                        + System.getProperty("http.proxyPort"));
            }
        }
    } catch (IOException e) {
        logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " ("
                + e.getClass().getName() + ")");
        if (System.getProperty("http.proxyHost") != null) {
            logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                    + System.getProperty("http.proxyPort"));
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    return cookie;

}

From source file:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }// ww w  .j  av  a2  s .co m
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:Main.java

/**
 * Issue a POST request to the server.//from  ww  w. j  av a  2s  .c o  m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    //Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();

        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:com.zf.util.Post_NetNew.java

/**
 * ?//ww w .  ja  v  a  2 s. c  om
 * 
 * @param pams
 * @param ip
 * @param port
 * @return
 * @throws Exception
 */
public static String pn(Map<String, String> pams, String ip, int port) throws Exception {
    if (null == pams) {
        return "";
    }
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Type.HTTP, addr);
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
    httpConn.setConnectTimeout(30000);
    httpConn.setReadTimeout(30000);
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}