Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

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

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

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  .  ja v a2 s . c om

    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:com.heraldapp.share.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from  ww  w  . ja  v a2s  . co  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    String response = "";
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        if (!method.equals("GET")) {
            // use method override
            params.putString("method", method);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    } catch (SocketTimeoutException e) {
        return response;
    }
    return response;
}

From source file:website.openeng.anki.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix,
        String method) {/*from  ww w.  jav  a  2s.co m*/
    try {
        URL url = new URL(UrlToFile);

        String extension = UrlToFile.substring(UrlToFile.length() - 4);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);
        urlConnection.setRequestProperty("Referer", "website.openeng.anki");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(60000);
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, context.getCacheDir());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

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  ww w.j a  v  a  2 s. c  om*/

    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:com.android.tools.idea.structure.MavenDependencyLookupDialog.java

@NotNull
private static List<String> searchMavenCentral(@NotNull String text) {
    try {//www. j  a v  a 2s.c o  m
        String url = String.format(MAVEN_CENTRAL_SEARCH_URL, RESULT_LIMIT, text);
        final HttpURLConnection urlConnection = HttpConfigurable.getInstance().openHttpConnection(url);
        urlConnection.setConnectTimeout(SEARCH_TIMEOUT);
        urlConnection.setReadTimeout(SEARCH_TIMEOUT);
        urlConnection.setRequestProperty("accept", "application/xml");

        InputStream inputStream = urlConnection.getInputStream();
        Document document;
        try {
            document = new SAXBuilder().build(inputStream);
        } finally {
            inputStream.close();
        }
        XPath idPath = XPath.newInstance("str[@name='id']");
        XPath versionPath = XPath.newInstance("str[@name='latestVersion']");
        List<Element> artifacts = (List<Element>) XPath.newInstance("/response/result/doc")
                .selectNodes(document);
        List<String> results = Lists.newArrayListWithExpectedSize(artifacts.size());
        for (Element element : artifacts) {
            try {
                String id = ((Element) idPath.selectSingleNode(element)).getValue();
                String version = ((Element) versionPath.selectSingleNode(element)).getValue();
                results.add(id + ":" + version);
            } catch (NullPointerException e) {
                // A result is missing an ID or version. Just skip it.
            }
        }
        return results;
    } catch (JDOMException e) {
        LOG.warn(e);
    } catch (IOException e) {
        LOG.warn(e);
    }
    return Collections.emptyList();
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * //from  w ww.j  ava 2s .c o m
  *    (  )
  * 
  *******************************************************************************/
public static String get_second_detail(final int position, final String string, final int url_image_size,
        final int comments, final int comments_page) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size
    /*+ "&comments="   + comments
    + "&comments_page="   + comments_page*/
            + "&consumer_key=" + Var.consumer_key;
    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        httpConn.setConnectTimeout(10000);
        int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONObject jsonObject = jObject.getJSONObject("photo");

            //            Log.i(TAG, "jsonObject " + jsonObject);

            Var.detail_nameMap.put(position, jsonObject.getString("name"));
            Var.detail_locationMap.put(position, jsonObject.getString("location"));
            Var.detail_ratingMap.put(position, jsonObject.getString("rating"));
            Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed"));
            Var.detail_votesMap.put(position, jsonObject.getString("votes_count"));
            Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count"));
            Var.detail_descriptionMap.put(position, jsonObject.getString("description"));
            Var.detail_cameraMap.put(position, jsonObject.getString("camera"));
            Var.detail_lensMap.put(position, jsonObject.getString("lens"));
            Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length"));
            Var.detail_isoMap.put(position, jsonObject.getString("iso"));
            Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed"));
            Var.detail_apertureMap.put(position, jsonObject.getString("aperture"));
            Var.detail_categoryMap.put(position, jsonObject.getString("category"));
            Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded"));
            Var.detail_takenMap.put(position, jsonObject.getString("taken_at"));
            Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type"));

            JSONObject jsonuser = jsonObject.getJSONObject("user");
            Var.detail_user_nameMap.put(position, jsonuser.getString("fullname"));
            Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url"));

            //     ( . .)
            /*JSONArray jsonArray = jObject.getJSONArray("comments");
            for(int i=0 ; i<jsonArray.length() ; i++){
               Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id"));
               Var.comment_body.add(jsonArray.getJSONObject(i).getString("body"));
                       
                JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                Var.comment_fullname.add(jsonuser.getString("fullname"));
                Var.comment_userpic_url.add(jsonuser.getString("userpic_url"));
            }*/

            /*            Log.i("Main", "feature   " +feature);
                        Log.i("Main", "filters   " +filters);
                        Log.i("Main", "categoryArr   " +Var.categoryArr);
                        Log.i("Main", "idArr   " +Var.idArr);
                        Log.i("Main", "image_urlArr   " +Var.image_urlArr);
                        Log.i("Main", "nameArr   " +Var.nameArr);
                        Log.i("Main", "ratingArr   " +Var.ratingArr);
                        Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
                        Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
                        Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
                        Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
                        Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
                        Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);*/
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:Main.java

public static String[] getUrlInfos(String urlAsString, int timeout) {
    try {/*ww w .j av a 2  s.co m*/
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent", "Mozilla/5.0 Gecko/20100915 Firefox/3.6.10");

        // on android we got problems because of this
        // so disable that for now
        //            hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        // default length of bufferedinputstream is 8k
        byte[] arr = new byte[K4];
        InputStream is = hConn.getInputStream();

        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        BufferedInputStream in = new BufferedInputStream(is, arr.length);
        in.read(arr);

        return getUrlInfosFromText(arr, hConn.getContentType());
    } catch (Exception ex) {
    }
    return new String[] { "", "" };
}

From source file:com.edgenius.wiki.Shell.java

public static String requestSpaceThemeName(String spaceUname) {
    try {/*from w  ww . ja v a  2s.c om*/
        log.info("Request shell theme for space {}", spaceUname);

        //reset last keyValidator value  - will use new one.
        HttpURLConnection conn = (HttpURLConnection) new URL(getThemeRequestURL(spaceUname)).openConnection();
        conn.setConnectTimeout(timeout);
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        int len;
        byte[] bytes = new byte[200];
        while ((len = is.read(bytes)) != -1) {
            writer.write(bytes, 0, len);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return new String(writer.toByteArray());
        }
    } catch (IOException e) {
        log.error("Unable to connect shell for theme name request", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return null;
}

From source file:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;//from   w  ww .  ja  v  a 2  s.co m
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer16(String hash) throws IOException {
    URL url;/*from   w  ww  .j a  v  a 2 s. c  om*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.connect();

    if (con.getResponseCode() != 200) {
        throw new IOException("Auth server rejected username and password");
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (!"OK".equals(reply)) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}