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.compomics.colims.core.util.AccessionConverter.java

/**
 * convenience method for opening a buffered reader to an url, standard
 * timeout is set to 500 milliseconds/*from ww w  .jav  a 2s. com*/
 *
 * @param aUrl the url to open a reader to
 * @return the buffered reader for reading the url
 * @throws IOException if the url could not be read
 */
public static BufferedReader openReader(String aUrl) throws IOException {
    URL myURL = new URL(aUrl);
    HttpURLConnection c = (HttpURLConnection) myURL.openConnection();
    c.setConnectTimeout(500);
    return new BufferedReader(new InputStreamReader(new BufferedInputStream(c.getInputStream()), "UTF-8"));
}

From source file:com.compomics.colims.core.util.AccessionConverter.java

public static BufferedInputStream openStream(String aURL) throws IOException {
    URL myURL = new URL(aURL);
    HttpURLConnection c = (HttpURLConnection) myURL.openConnection();
    c.setConnectTimeout(500);
    return new BufferedInputStream(c.getInputStream());

}

From source file:be.roots.taconic.pricingguide.util.HttpUtil.java

private static HttpURLConnection getInputStreamFor(String urlAsString, String userName, String password)
        throws IOException {
    LOGGER.info(/*  w  ww .  j  a v  a 2 s.c  o m*/
            REQUEST_METHOD + "ting data from url: " + urlAsString + " with timeout set to " + CONNECT_TIMEOUT);

    final URL url = new URL(urlAsString);
    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod(REQUEST_METHOD);
    con.setConnectTimeout(CONNECT_TIMEOUT);

    if (userName != null || password != null) {
        final String encoded = Base64.encode(userName + ":" + password);
        con.setRequestProperty("Authorization", "Basic " + encoded);
    }

    final int responseCode = con.getResponseCode();

    LOGGER.info("Response code: " + responseCode);
    return con;
}

From source file:itdelatrisu.opsu.downloads.BloodcatServer.java

/**
 * Returns a JSON object from a URL.// ww  w  . jav a 2s  . co m
 * @param url the remote URL
 * @return the JSON object
 * @author Roland Illig (http://stackoverflow.com/a/4308662)
 */
public static JSONObject readJsonFromUrl(URL url) throws IOException {
    // open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(Download.CONNECTION_TIMEOUT);
    conn.setReadTimeout(Download.READ_TIMEOUT);
    conn.setUseCaches(false);
    try {
        conn.connect();
    } catch (SocketTimeoutException e) {
        ErrorHandler.error("Connection to server timed out.", e, false);
        throw e;
    }

    if (Thread.interrupted())
        return null;

    // read JSON
    JSONObject json = null;
    try (InputStream in = conn.getInputStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = rd.read()) != -1)
            sb.append((char) c);
        json = new JSONObject(sb.toString());
    } catch (SocketTimeoutException e) {
        ErrorHandler.error("Connection to server timed out.", e, false);
        throw e;
    } catch (JSONException e1) {
        ErrorHandler.error("Failed to create JSON object.", e1, true);
    }
    return json;
}

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

/**
 * ?/*from  w ww.j  a va  2  s.  c o m*/
 * 
 * @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();
}

From source file:Main.java

public static void server2mobile(Context context, String type) {

    String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type;
    try {/*from ww w.java 2s. c o m*/
        URL url = new URL(serverPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");

        int code = conn.getResponseCode();
        Log.d("code", code + "");
        if (code == 200) {
            InputStream is = conn.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            conn.disconnect();

            String result = new String(baos.toByteArray());
            String[] results = result.split("[$]");
            for (String r : results) {
                if (r.length() != 0) {
                    URL json = new URL(r);
                    HttpURLConnection con = (HttpURLConnection) json.openConnection();
                    con.setConnectTimeout(5000);
                    con.setRequestMethod("GET");
                    int co = con.getResponseCode();
                    if (co == 200) {
                        File jsonFile;
                        if (r.endsWith("clear.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/clear.json");
                        } else if (r.endsWith("crowd.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json");
                        } else if (r.endsWith("trouble.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json");
                        } else {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/control.json");
                        }

                        if (jsonFile.exists())
                            jsonFile.delete();
                        jsonFile.createNewFile();
                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(con.getInputStream(), "gb2312"));
                                BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) {
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                writer.write(line);
                            }
                        }

                    }
                    con.disconnect();
                }
            }

        }

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

}

From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java

public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {//from   ww w.j  av a 2  s.c  o  m

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}

From source file:net.daporkchop.porkbot.util.HTTPUtils.java

private static HttpURLConnection createUrlConnection(@NonNull URL url) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(15000);//from w  w  w  .ja  v  a 2s .c om
    connection.setUseCaches(false);
    return connection;
}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {//w w w  .  j  av a  2s.  c  om
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:massbank.svn.MSDBUpdateUtil.java

/**
 *
 */// w w w  . j  a va2 s  .  co m
public static boolean updateSubStructData(String serverUrl) {
    boolean ret = true;
    String cgiUrl = serverUrl + "cgi-bin/GenSubstructure.cgi";
    try {
        URL url = new URL(cgiUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(10 * 1000);
        con.setReadTimeout(60 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = "";
        StringBuilder res = new StringBuilder();
        while ((line = in.readLine()) != null) {
            res.append(line);
        }
        if (res.indexOf("OK") == -1) {
            ret = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        ret = false;
    }
    return ret;
}