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.alexkli.jhb.Worker.java

@Override
public void run() {
    try {// ww w. j  av  a 2s  .  c  om
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:com.koodroid.chicken.KooDroidHelper.java

public void checkForUpdateOnBackgroundThread(final MainActivity activity) {
    if (mAlreadyCheckedForUpdates) {
        return;/* w ww.j ava 2  s .c o  m*/
    }
    mAlreadyCheckedForUpdates = true;
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            SharedPreferences prefs = activity.getSharedPreferences(KooDroidHelper.class.getName(),
                    Context.MODE_PRIVATE);
            Random random = new Random();
            long interval = random.nextInt(7) + 3; // [3, 10)
            long timestamp = prefs.getLong("LastCheckTimestamp", 0);
            long now = System.currentTimeMillis();
            if ((now - timestamp < interval * 24 * 60 * 60 * 1000) && !DEBUG) {
                return null;
            }
            prefs.edit().putLong("LastCheckTimestamp", now).commit();
            HttpURLConnection urlConnection = null;
            BufferedReader in = null;
            try {

                URL url = new URL(mUpdateUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(60000);
                urlConnection.setReadTimeout(60000);
                urlConnection.setUseCaches(false);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200) {
                    InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
                    in = new BufferedReader(reader);
                    StringBuilder response = new StringBuilder();
                    for (String line = in.readLine(); line != null; line = in.readLine()) {
                        response.append(line);
                    }

                    try {
                        JSONObject jsonObj = new JSONObject(response.toString());
                        mLatestVersion = jsonObj.getString("version_code");
                        mDownloadUrl = jsonObj.getString("download_url");
                    } catch (JSONException e) {
                        System.out.println("Json parse error");
                        e.printStackTrace();
                    }
                    //                        
                    //                        JSONTokener jsonParser = new JSONTokener(response.toString());    
                    //                        // ?json?JSONObject    
                    //                        // ??"name" : nextValue"yuanzhifei89"String    
                    //                        JSONObject person = (JSONObject) jsonParser.nextValue();    
                    //                        // ?JSON?    
                    //                        person.getJSONArray("phone");    
                    //                        person.getString("name");    
                    //                        person.getInt("age");    
                    //                        person.getJSONObject("address");    
                    //                        person.getBoolean("married");    
                    //                        
                    //mLatestVersion = response.toString();
                    int versionCode = Integer.valueOf(mLatestVersion);
                    mUpdateAvailable = Integer.valueOf(mLatestVersion) > Integer
                            .valueOf(getPackageVersionCode(activity));
                }
            } catch (Exception e) {
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //maybeShowUpdateDialog(activity);
        }
    }.execute();
}

From source file:net.bither.bitherj.api.DownloadFile.java

private boolean downloadUrlToFile(String urlString, File file) throws IOException, HttpRequestException {
    //  disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    OutputStream outputStream = null;
    try {/*w  ww .  j  ava2s  .  c  om*/
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(HttpSetting.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(HttpSetting.HTTP_SO_TIMEOUT);
        String sCookies = getCookie();

        urlConnection.setRequestProperty("Cookie", sCookies);
        int httpCode = urlConnection.getResponseCode();
        if (httpCode != 200) {
            throw new HttpRequestException("http exception " + httpCode);
        }

        outputStream = new FaultHidingOutputStream(new FileOutputStream(file));
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        throw e;
    } finally {

        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (hasErrors) {
                deleteIfExists(file);
            }

        } catch (final IOException e) {
            throw e;
        }
    }
}

From source file:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java

private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod)
        throws ConnectionException {
    HttpURLConnection urlConnection;
    try {/*from w  w  w. jav a  2  s .c o  m*/
        URIBuilder b = new URIBuilder(BASE_URL);
        b.addParameters(params);
        URL url = b.build().toURL();
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(responseMethod);
        urlConnection.setReadTimeout(TIME_OUT_LENGTH);
        urlConnection.setConnectTimeout(TIME_OUT_LENGTH);
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(urlConnection.getResponseMessage());
        return urlConnection;
    } catch (URISyntaxException | IOException ex) {
        throw new ConnectionException(ex);
    }
}

From source file:com.rapleaf.api.personalization.RapleafApi.java

/**
 * @param urlStr      String email built in query with URLEncoded email
 * @param showAvailable  If true, return the string "Data Available" for
 *                     fields the account is not subscribed to but for which Rapleaf has data
 * @return            Returns a JSONObject hash from fields onto field values
 * @throws Exception  Throws error code on all HTTP statuses outside of 200 <= status < 300
 *///from  ww  w.j a  va  2s  .  co m
protected JSONObject getJsonResponse(String urlStr, boolean showAvailable) throws Exception {
    if (showAvailable) {
        urlStr = urlStr + "&show_available=true";
    }
    URL url = new URL(urlStr);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestProperty("User-Agent", getUserAgent());
    handle.setConnectTimeout(timeout);
    handle.setReadTimeout(timeout);
    BufferedReader in = new BufferedReader(new InputStreamReader(handle.getInputStream()));
    String responseBody = in.readLine();
    in.close();
    int responseCode = handle.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
        throw new Exception("Error Code " + responseCode + ": " + responseBody);
    }
    if (responseBody == null || responseBody.equals("")) {
        responseBody = "{}";
    }
    return new JSONObject(responseBody);
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Make remote request to get all calls stored in Cozy
 *//*from  www .j  av a 2 s  .  c o  m*/
public String getRemoteCalls() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                Call.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE,
                            "Reading calls on Cozy " + i + "/" + jsonArray.length() + "..."));
                    JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Call call = Call.getByRemoteId(callJson.get("_id").toString());
                    if (call == null) {
                        call = new Call(callJson);
                    } else {
                        call.setRemoteId(callJson.getString("_id"));
                        call.setCallerId(callJson.getString("callerId"));
                        call.setCallerNumber(callJson.getString("callerNumber"));
                        call.setDuration(callJson.getLong("duration"));
                        call.setDateAndTime(callJson.getString("dateAndTime"));
                        call.setType(callJson.getInt("type"));
                    }

                    call.save();

                    allCalls.add(call);
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

public void sendChangesToCozy() {
    List<Call> unSyncedCalls = Call.getAllUnsynced();
    int i = 0;/*from   w ww  .  ja v a  2  s. co m*/
    for (Call call : unSyncedCalls) {
        URL urlO = null;
        try {
            JSONObject jsonObject = call.toJsonObject();
            mBuilder.setProgress(unSyncedCalls.size(), i, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new CallSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_calls_send_changes)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                call.setRemoteId(result);
                call.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        }
        i++;
    }
}

From source file:co.forsaken.api.json.JsonWebCall.java

private boolean canConnect() throws Exception {
    try {/*from w  w w.  j  a  v  a  2  s.c  o m*/
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(_url).openConnection();
        con.setRequestMethod("HEAD");

        con.setConnectTimeout(2000);

        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new Exception("Service " + _url + " unavailable, oh no!");
        }
        return true;
    } catch (java.net.SocketTimeoutException e) {
        throw new Exception("Service " + _url + " unavailable, oh no!", e);
    } catch (java.io.IOException e) {
        throw new Exception("Service " + _url + " unavailable, oh no!", e);
    }
}

From source file:com.zjut.material_wecenter.Client.java

/**
 * doPost ??POST//from   w ww. j  a  v a  2s.c o  m
 * @param URL URL
 * @param params ?
 * @return ?NULL
 */
private String doPost(String URL, Map<String, String> params) {
    // 
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // ?
    try {
        URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // ??
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // ?
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // ?Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // ??
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            return new String(byteArrayOutputStream.toByteArray());
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}

From source file:net.bither.api.DownloadFile.java

private boolean downloadUrlToFile(String urlString, File file) throws IOException, HttpRequestException {
    disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    OutputStream outputStream = null;
    try {//from   w  w  w. jav  a 2  s . c  om
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(HttpSetting.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(HttpSetting.HTTP_SO_TIMEOUT);
        String sCookies = getCookie();
        LogUtil.d("cookie", sCookies);
        urlConnection.setRequestProperty("Cookie", sCookies);
        int httpCode = urlConnection.getResponseCode();
        if (httpCode != 200) {
            throw new HttpRequestException("http exception " + httpCode);
        }

        outputStream = new FaultHidingOutputStream(new FileOutputStream(file));
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        throw e;
    } finally {

        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (hasErrors) {
                deleteIfExists(file);
            }

        } catch (final IOException e) {
            throw e;
        }
    }
}