List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Prepares a connection to the server.//from w w w . ja va 2 s . com * @param extraHeaders extra headers to add to the request * @return the unopened connection * @throws IOException */ protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException { // create URLConnection HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy); con.setConnectTimeout(connectionTimeoutMillis); con.setReadTimeout(readTimeoutMillis); con.setAllowUserInteraction(false); con.setDefaultUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setInstanceFollowRedirects(true); con.setRequestMethod("POST"); // do stuff for ssl if (HttpsURLConnection.class.isInstance(con)) { HttpsURLConnection https = HttpsURLConnection.class.cast(con); if (hostNameVerifier != null) { https.setHostnameVerifier(hostNameVerifier); } if (sslContext != null) { https.setSSLSocketFactory(sslContext.getSocketFactory()); } } // add headers con.setRequestProperty("Content-Type", "application/json-rpc"); for (Entry<String, String> entry : headers.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } for (Entry<String, String> entry : extraHeaders.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } // return it return con; }
From source file:com.atinternet.tracker.TVTrackingPlugin.java
@Override protected void execute(Tracker tracker) { this.tracker = tracker; try {//from w w w .ja va 2 s. co m if (sessionIsExpired()) { setDirectCampaignToRemanent(); URL url = new URL(tracker.TVTracking().getCampaignURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setDoInput(true); connection.connect(); response = getTvTrackingResponse(stringifyTvTResponse(connection), connection); connection.disconnect(); } else { response = getTvTrackingResponse( Tracker.getPreferences().getString(TrackerConfigurationKeys.DIRECT_CAMPAIGN_SAVED, null), null); } Tool.executeCallback(tracker.getListener(), Tool.CallbackType.partner, "TV Tracking : " + response); Tracker.getPreferences().edit() .putLong(TrackerConfigurationKeys.LAST_TVT_EXECUTE_TIME, System.currentTimeMillis()).apply(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.flexive.war.beans.admin.RssProviderBean.java
/** * Fetch and parse a news feed (currently only tested with blog.flexive.org). * * @param url the feed URL//from ww w . j a va 2 s. c o m * @param maxItems the maximum number of items returned * @return the news items */ private List<RssEntry> fetchFeed(String url, int maxItems) { HttpURLConnection urlConnection = null; InputStream in = null; try { // open url urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setConnectTimeout(2000); in = urlConnection.getInputStream(); // parse RSS feed final DocumentBuilder domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document doc = domBuilder.parse(new InputSource(in)); // iterate over items final NodeList items = doc.getElementsByTagName("item"); final int numItems = Math.min(items.getLength(), maxItems); final List<RssEntry> result = new ArrayList<RssEntry>(numItems); for (int i = 0; i < numItems; i++) { final NodeList childNodes = items.item(i).getChildNodes(); String title = null; String link = null; // find title and link children for (int j = 0; j < childNodes.getLength(); j++) { final Node child = childNodes.item(j); if ("title".equals(child.getNodeName())) { title = child.getTextContent(); if (link != null) { break; } } else if ("link".equals(child.getNodeName())) { link = child.getTextContent(); if (title != null) { break; } } } if (title != null && link != null) { result.add(new RssEntry(title, link)); } } return result; } catch (IOException e) { LOG.error("Failed to fetch stream from " + url + ": " + e.getMessage(), e); return new ArrayList<RssEntry>(0); } catch (SAXException e) { LOG.error("Failed to parse XML stream: " + url + ": " + e.getMessage(), e); return new ArrayList<RssEntry>(0); } catch (ParserConfigurationException e) { LOG.error("Failed to create parser: " + url + ": " + e.getMessage(), e); return new ArrayList<RssEntry>(0); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.warn("Failed to close input stream: " + e.getMessage(), e); } } if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
public void sendChangesToCozy() { List<Expense> unSyncedExpenses = Expense.getAllUnsynced(); int i = 0;/*www . jav a 2 s . c o m*/ for (Expense expense : unSyncedExpenses) { URL urlO = null; try { JSONObject jsonObject = expense.toJsonObject(); mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault().post( new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone))); 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"); expense.setRemoteId(result); expense.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }
From source file:com.android.browser.search.OpenSearchSearchEngine.java
/** * Executes a GET request and returns the response content. * * @param urlString Request URI.//from ww w . jav a 2 s. c o m * @return The response content. This is the empty string if the response * contained no content. */ public String readUrl(String urlString) { try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", USER_AGENT); urlConnection.setConnectTimeout(HTTP_TIMEOUT_MS); if (urlConnection.getResponseCode() == 200) { final Charset responseCharset; try { responseCharset = ResponseUtils.responseCharset(urlConnection.getContentType()); } catch (UnsupportedCharsetException ucse) { Log.i(TAG, "Unsupported response charset", ucse); return null; } catch (IllegalCharsetNameException icne) { Log.i(TAG, "Illegal response charset", icne); return null; } byte[] responseBytes = Streams.readFully(urlConnection.getInputStream()); return new String(responseBytes, responseCharset); } else { Log.i(TAG, "Suggestion request failed"); return null; } } catch (IOException e) { Log.w(TAG, "Error", e); return null; } }
From source file:com.cydroid.coreframe.web.img.fetcher.ImageFetcher.java
public Bitmap getImage(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10 * 1000);// w ww . jav a2s. co m conn.setConnectTimeout(10 * 1000); conn.setRequestMethod("GET"); InputStream is = null; if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { is = conn.getInputStream(); } else { is = null; } if (is == null) { throw new RuntimeException("stream is null"); } else { try { byte[] data = readStream(is); if (data != null) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); return bitmap; } } catch (Exception e) { e.printStackTrace(); } is.close(); return null; } }
From source file:au.org.ala.fielddata.mobile.service.FieldDataServiceClient.java
public boolean ping(int timeoutInMillis) { InputStream in = null;/*from w w w .j ava 2s . c om*/ HttpURLConnection conn = null; boolean canPing = true; try { URL url = new URL(getServerUrl() + pingUrl); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(timeoutInMillis); //conn.setReadTimeout(timeoutInMillis); in = conn.getInputStream(); while (in.read() != -1) { } } catch (Exception e) { canPing = false; } finally { try { close(in); close(conn); } catch (Exception e) { canPing = false; } } return canPing; }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFolders() { //File.deleteAllFolders(); URL urlO = null;//from w w w .java 2s. c om try { urlO = new URL(folderUrl); 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) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(folderJson.get("_id").toString()); if (file == null) { file = new File(folderJson, true); } else { file.setName(folderJson.getString("name")); file.setPath(folderJson.getString("path")); file.setCreationDate(folderJson.getString("creationDate")); file.setLastModification(folderJson.getString("lastModification")); file.setTags(folderJson.getString("tags")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing remote folder : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName())); file.save(); createFolder(file.getPath(), file.getName()); allFiles.add(file); } } else { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response")); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java
/** * Performs the web site monitoring by checking the response code of the site's URL. * //from ww w. j a v a2s .c o m * @param build * the build * @param launcher * the launcher * @param listener * the listener * @return true if all sites give success response codes, false otherwise * @throws InterruptedException * when there's an interruption * @throws IOException * when there's an IO error */ @Override public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { List<Result> results = new ArrayList<Result>(); SiteMonitorDescriptor descriptor = (SiteMonitorDescriptor) getDescriptor(); if (CookieHandler.getDefault() == null) { CookieHandler.setDefault(new CookieManager()); } boolean hasFailure = false; for (Site site : mSites) { Integer responseCode = null; Status status; String note = ""; HttpURLConnection connection = null; try { connection = getConnection(site.getUrl()); if (site.getTimeout() != null) { connection.setConnectTimeout(site.getTimeout() * MILLISECS_IN_SECS); } else { connection.setConnectTimeout(descriptor.getTimeout() * MILLISECS_IN_SECS); } responseCode = connection.getResponseCode(); List<Integer> successResponseCodes = descriptor.getSuccessResponseCodes(); if (site.getSuccessResponseCodes() != null && site.getSuccessResponseCodes().size() > 0) { successResponseCodes = site.getSuccessResponseCodes(); } if (successResponseCodes.contains(responseCode)) { status = Status.UP; } else { status = Status.ERROR; } } catch (SocketTimeoutException ste) { listener.getLogger().println(ste + " - " + ste.getMessage()); status = Status.DOWN; } catch (Exception e) { note = e + " - " + e.getMessage(); listener.getLogger().println(note); status = Status.EXCEPTION; } finally { if (connection != null) { connection.disconnect(); } } note = "[" + status + "] " + note; listener.getLogger() .println(Messages.SiteMonitor_Console_URL() + site.getUrl() + ", " + Messages.SiteMonitor_Console_ResponseCode() + responseCode + ", " + Messages.SiteMonitor_Console_Status() + status); if (!hasFailure && status != Status.UP) { hasFailure = true; } Result result = new Result(site, responseCode, status, note); results.add(result); } build.addAction(new SiteMonitorRootAction(results)); hudson.model.Result result; if (hasFailure) { result = hudson.model.Result.FAILURE; } else { result = hudson.model.Result.SUCCESS; } build.setResult(result); // the return value is not used when this class implements a Recorder, // it's left here just in case this class switches to a Builder. // http://n4.nabble.com/how-can-a-Recorder-mark-build-as-failure-td1746654.html return !hasFailure; }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
/** * Make remote request to get all loyalty cards stored in Cozy *///from ww w . j av a 2 s . com public String getRemoteExpenses() { 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 ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored.")); Expense.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE, "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value"); Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString()); if (expense == null) { expense = new Expense(expenseJson); } else { expense.setRemoteId(expenseJson.getString("_id")); expense.setAmount(expenseJson.getDouble("amount")); expense.setCategory(expenseJson.getString("category")); expense.setDate(expenseJson.getString("date")); if (expenseJson.has("deviceId")) { expense.setDeviceId(expenseJson.getString("deviceId")); } else { expense.setDeviceId(Device.registeredDevice().getLogin()); } } expense.save(); if (expenseJson.has("receipts")) { JSONArray receiptsArray = expenseJson.getJSONArray("receipts"); for (int j = 0; j < receiptsArray.length(); j++) { JSONObject recJsonObject = receiptsArray.getJSONObject(i); Receipt receipt = new Receipt(); receipt.setBase64(recJsonObject.getString("base64")); receipt.setExpense(expense); receipt.setName(""); receipt.save(); } } } catch (JSONException e) { EventBus.getDefault() .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }