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.nhncorp.lucy.security.xss.listener.SecurityUtils.java

public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) {
    // cache ?  ?.
    String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl);
    //System.out.println("getContentTypeFromCache : " + result);
    if (StringUtils.isNotEmpty(result)) {
        return result;
    }//from  w w  w  .j a v  a2 s  . com

    HttpURLConnection con = null;

    try {
        URL url = new URL(strUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("HEAD");
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.connect();

        int resCode = con.getResponseCode();

        if (resCode != HttpURLConnection.HTTP_OK) {
            System.err.println("error");
        } else {
            result = con.getContentType();
            //System.out.println("content-type from response header: " + result);

            if (result != null) {
                contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return result;

}

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

public static String doPut(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", contentTypeURLENCODED);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);//from   ww  w  . ja  v  a 2  s. co m
    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);
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

public static boolean ping(String url, int maxSecs) {

    long startMs = System.currentTimeMillis();
    try {/*  w ww. j av a  2  s.c o  m*/
        while (maxSecs >= ((System.currentTimeMillis() - startMs) / 1000)) {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                if (200 <= responseCode && responseCode <= 399) {
                    return true;
                } else {
                    Thread.sleep(2000);
                }
            } catch (IOException exception) {
                Thread.sleep(2000);
            }

        }
    } catch (InterruptedException ie) {
        // IGNORE
    }
    return false;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Delete specified dataset/*from  ww w  .  j a v  a  2 s .  c  o  m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void deleteDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("delete dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("DELETE");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from w  ww.j a v a  2  s.c  o m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // 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);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./*  w w w .  ja v a  2s .  c o m*/
 *
 * @param url The exact URL to request.
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 * @author Sections of this code contributed by jTribe (http://jtribe.com.au)
 */
protected static synchronized String getUrlContent(String sUrl, String email, String pword)
        throws ApiException {
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    String userPassword = email + ":" + pword;
    String encoding = Base64Coder.encodeString(userPassword);
    try {
        URL url = new URL(sUrl);

        System.setProperty("http.keepAlive", "false");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setRequestProperty("User-Agent", sUserAgent);
        connection.setRequestMethod("GET");

        //Get response code
        int responseCode = connection.getResponseCode();

        if (responseCode != HTTP_STATUS_OK) {
            throw new ApiException("Invalid response from server: " + connection.getResponseMessage());
        }

        // Pull content stream from response
        InputStream inputStream = connection.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        // Return result from buffered stream
        return new String(content.toByteArray());
    } catch (IOException e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public static String getRedirectUrl(REGION region) {
    String result = "";

    switch (region) {
    case EU:// ww w . jav  a  2s.c  o m
        result = amazonEuDomain;
        break;
    case USA:
        result = amazonUsaDomain;
        break;
    case ASIA:
        result = amazonAsiaDomain;
        break;
    }

    System.out.println("Trying to get real IP address of " + result);
    try {
        /*
        HttpHead headRequest = new HttpHead(result);
        HttpClient client = new DefaultHttpClient();
         HttpResponse response = client.execute(headRequest);
         final int statusCode = response.getStatusLine().getStatusCode();
         if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
             statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
         {
             String location = response.getHeaders("Location")[0].toString();
             String redirecturl = location.replace("Location: ", "");
             result = redirecturl;
         }
        */

        URL url = new URL(result);
        HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection();
        httpGetCon.setInstanceFollowRedirects(false);
        httpGetCon.setRequestMethod("GET");
        httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds

        httpGetCon.setRequestProperty("User-Agent", USER_AGENT);

        int status = httpGetCon.getResponseCode();
        System.out.println("code: " + status);
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            result = httpGetCon.getHeaderField("Location");

    } catch (Exception e) {
        System.out.println("Exception is fired in redirector getter. error:" + e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Real IP address is " + result);
    return result;
}

From source file:Main.java

public static String uploadFile(String filePath, String requestURL) {

    String result = "";
    File file = new File(filePath);

    try {//from  ww  w  .j  a v  a  2  s.  co  m
        HttpURLConnection connection = initHttpURLConn(requestURL);

        if (filePath != null) {
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            StringBuffer sb = new StringBuffer();
            InputStream is = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            dos.flush();
            is.close();
            int res = connection.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                Log.e(TAG, "request success");
                InputStream input = connection.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }

                result = sb1.toString();
                Log.d(TAG, "result: " + result);

                input.close();
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;

}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }/*from w ww  .  j a  va2 s .co m*/

    String scheme = uri.getScheme();
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);

        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

public static String get(String endpoint) {
    URL url = null;//from w  w  w. ja va 2s .co m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        //Fail silently
    }

    HttpURLConnection conn;

    long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
    for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) {
        try {
            conn = makeGetConnection(url);

            // handle the response
            int status = conn.getResponseCode();

            if (status == 200) {

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();

                if (null != conn) {
                    conn.disconnect();
                }

                return sb.toString();
            }

            else if (500 > status) {
                if (null != conn) {
                    conn.disconnect();
                }
                return null;
            }
        } catch (IOException e) {
            try {
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Thread.currentThread().interrupt();
            }
            // increase backoff exponentially
            backoff *= 2;
        }
    }

    return null;
}