Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

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

/**
 * ?//from  w w  w. j av  a  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: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);
    connection.setUseCaches(false);/*from w  w  w .j av a 2s.co  m*/
    return connection;
}

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 {//w  w  w  .  ja v  a 2 s .com

        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:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {/* ww w.j  a  v a 2s  .com*/
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:massbank.svn.MSDBUpdateUtil.java

/**
 *
 *//*from  w w  w  .  j a  v  a  2 s.com*/
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;
}

From source file:com.example.admin.processingboilerplate.JsonIO.java

public static StringBuilder loadString(String url) {
    StringBuilder sb = new StringBuilder();
    try {//from   w w  w. j ava 2s .co m
        URLConnection uc = (new URL(url)).openConnection();
        HttpURLConnection con = url.startsWith("https") ? (HttpsURLConnection) uc : (HttpURLConnection) uc;
        try {
            con.setReadTimeout(6000);
            con.setConnectTimeout(6000);
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setRequestProperty("User-Agent", USER_AGENT);
            sb = load(con);
        } catch (IOException e) {
            Log.e("loadJson", e.getMessage(), e);
        } finally {
            con.disconnect();
        }
    } catch (IOException e) {
        Log.e("loadJson", e.getMessage(), e);
    }
    return sb;
}

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

/**
 * Returns a JSON object from a URL.//from  w  w  w.  jav a 2 s .c o 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:Main.java

private static InputStream getInputStreamFromUrl_V9(Context paramContext, String paramString) {
    if (confirmDownload(paramContext, paramString)) {
        try {//from   www  . ja  v a2s  .  co  m

            URL localURL = new URL(paramString);
            HttpURLConnection localHttpURLConnection2 = (HttpURLConnection) localURL.openConnection();
            localHttpURLConnection2.setRequestProperty("Accept-Charset", "UTF-8");
            localHttpURLConnection2.setReadTimeout(30000);
            localHttpURLConnection2.setConnectTimeout(30000);
            localHttpURLConnection2.setRequestMethod("GET");
            localHttpURLConnection2.setDoInput(true);
            localHttpURLConnection2.connect();
            return localHttpURLConnection2.getInputStream();

        } catch (Throwable localThrowable) {

            localThrowable.printStackTrace();
            return null;

        }
    } else {
        return null;
    }
}

From source file:com.uk_postcodes.api.Postcode.java

/**
 * Get the postcode closest to the location.
 * @param location The device's location
 * @return the closest postcode//from  w  w w .  jav a 2 s. c  o m
 * @throws Exception
 */
public static String forLocation(Location location) throws Exception {
    String address = String.format(CALL, location.getLatitude(), location.getLongitude());

    Log.d("Postcode", "Calling: " + address);

    URL callUrl = new URL(address);
    HttpURLConnection callConnection = (HttpURLConnection) callUrl.openConnection();
    // The ten-second rule:
    // If there's no data in 10s (or TIMEOUT), assume the worst.
    callConnection.setReadTimeout(10000);
    // Set the request method to GET.
    callConnection.setRequestMethod("GET");
    int code = callConnection.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new Exception("A non-200 code was returned: " + code);
    }

    String responseStr;
    responseStr = IOUtils.toString(callConnection.getInputStream());
    callConnection.disconnect();

    JsonParser jp = new JsonParser();
    JsonElement response = jp.parse(responseStr);
    return response.getAsJsonObject().get("postcode").getAsString();
}

From source file:com.book.jtm.chap03.HttpClientDemo.java

public static void sendRequest(String method, String url) throws IOException {
    InputStream is = null;/*  w w w.  j  a v a 2  s .c  o m*/
    try {
        URL newUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();
        // ?10
        conn.setReadTimeout(10000);
        // 15
        conn.setConnectTimeout(15000);
        // ?,GET"GET",post"POST"
        conn.setRequestMethod("GET");
        // ??
        conn.setDoInput(true);
        // ??,????
        conn.setDoOutput(true);
        // Header
        conn.setRequestProperty("Connection", "Keep-Alive");
        // ?
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("username", "mr.simple"));
        paramsList.add(new BasicNameValuePair("pwd", "mypwd"));
        writeParams(conn.getOutputStream(), paramsList);

        // ?
        conn.connect();
        is = conn.getInputStream();
        // ?
        String result = convertStreamToString(is);
        Log.i("", "###  : " + result);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}