List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.mabi87.httprequestbuilder.HTTPRequest.java
/** * @throws IOException//ww w. ja v a 2s.co m * throws from HttpURLConnection method. * @return the HTTPResponse object */ private HTTPResponse post() throws IOException { URL url = new URL(mPath); HttpURLConnection lConnection = (HttpURLConnection) url.openConnection(); lConnection.setReadTimeout(mReadTimeoutMillis); lConnection.setConnectTimeout(mConnectTimeoutMillis); lConnection.setRequestMethod("POST"); lConnection.setDoInput(true); lConnection.setDoOutput(true); OutputStream lOutStream = lConnection.getOutputStream(); BufferedWriter lWriter = new BufferedWriter(new OutputStreamWriter(lOutStream, "UTF-8")); lWriter.write(getQuery(mParameters)); lWriter.flush(); lWriter.close(); lOutStream.close(); HTTPResponse response = readPage(lConnection); return response; }
From source file:msearch.filmlisten.MSFilmlisteLesen.java
private InputStream getInputStreamForLocation(String source) throws Exception { InputStream in;/*from w ww. ja va 2 s . c o m*/ long size = 0; final URI uri; if (source.startsWith("http")) { uri = new URI(source); //remote address for internet download HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestProperty("User-Agent", MSConfig.getUserAgent()); if (conn.getResponseCode() < 400) { size = conn.getContentLengthLong(); } in = new SizeInputStream(conn.getInputStream(), size, uri.toASCIIString()); } else { //local file notifyProgress(source, "Download", PROGRESS_MAX); in = new FileInputStream(source); } return in; }
From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java
private OidcDiscoveryCachedResource fetchResource(final String url, final long timeNow, final OidcDiscoveryCachedResource cached) throws IOException { final URL location = new URL(url); final OidcResource oidcResource; { // setup url connection and resolve final HttpURLConnection conn = (HttpURLConnection) location.openConnection(); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setUseCaches(false);//from w ww. j a v a2s. c o m if (cached != null) { if (cached.lastModified.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_MODIFIED_SINCE, cached.lastModified.get()); } if (cached.etag.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_NONE_MATCH, cached.etag.get()); } } oidcResource = resolve(conn); } // build cache entry from resource if (oidcResource.statusCode == 304) { return new OidcDiscoveryCachedResource(timeNow, cached); } else { return new OidcDiscoveryCachedResource(timeNow, Option.of(oidcResource.lastModifiedHeader), Option.of(oidcResource.etagHeader), ImmutableList.copyOf(oidcResource.certs), url, new String(oidcResource.content, StandardCharsets.UTF_8)); } }
From source file:edu.usf.cutr.opentripplanner.android.pois.Nominatim.java
public JSONArray requestPlaces(String paramName, String left, String top, String right, String bottom) { StringBuilder builder = new StringBuilder(); String encodedParamName;//ww w. jav a 2s.co m String encodedParamLeft = ""; String encodedParamTop = ""; String encodedParamRight = ""; String encodedParamBottom = ""; try { encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING); if ((left != null) && (top != null) && (right != null) && (bottom != null)) { encodedParamLeft = URLEncoder.encode(left, OTPApp.URL_ENCODING); encodedParamTop = URLEncoder.encode(top, OTPApp.URL_ENCODING); encodedParamRight = URLEncoder.encode(right, OTPApp.URL_ENCODING); encodedParamBottom = URLEncoder.encode(bottom, OTPApp.URL_ENCODING); } } catch (UnsupportedEncodingException e1) { Log.e(OTPApp.TAG, "Error encoding Nominatim request"); e1.printStackTrace(); return null; } request += "&q=" + encodedParamName; if ((left != null) && (top != null) && (right != null) && (bottom != null)) { request += "&viewbox=" + encodedParamLeft + "," + encodedParamTop + "," + encodedParamRight + "," + encodedParamBottom; request += "&bounded=1"; } request += "&key=" + mApiKey; Log.d(OTPApp.TAG, request); HttpURLConnection urlConnection = null; try { URL url = new URL(request); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(OTPApp.TAG, "Error obtaining Nominatim response, status code: " + status); } } catch (IOException e) { e.printStackTrace(); Log.e(OTPApp.TAG, "Error obtaining Nominatim response" + e.toString()); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } Log.d(OTPApp.TAG, builder.toString()); JSONArray json = null; try { json = new JSONArray(builder.toString()); } catch (JSONException e) { Log.e(OTPApp.TAG, "Error parsing Nominatim data " + e.toString()); } return json; }
From source file:eu.codeplumbers.cosi.services.CosiNoteService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiNoteService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // delete all local notes new Delete().from(Note.class).execute(); // cozy register device url this.url = device.getUrl() + "/ds-api/request/note/cosiall/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();//ww w. ja va2 s . c om if (isNetworkAvailable()) { try { URL urlO = new URL(url); 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++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value"); Note note = Note.getByRemoteId(noteJson.get("_id").toString()); if (note == null) { note = new Note(noteJson); } else { boolean versionIncremented = note.getVersion() < Integer .valueOf(noteJson.getString("version")); int modifiedOnServer = DateUtils.compareDateStrings( Long.valueOf(note.getLastModificationValueOf()), noteJson.getLong("lastModificationValueOf")); if (versionIncremented || modifiedOnServer == -1) { note.setTitle(noteJson.getString("title")); note.setContent(noteJson.getString("content")); note.setCreationDate(noteJson.getString("creationDate")); note.setLastModificationDate(noteJson.getString("lastModificationDate")); note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf")); note.setParentId(noteJson.getString("parent_id")); // TODO: 10/3/16 // handle note paths note.setPath(noteJson.getString("path")); note.setVersion(Integer.valueOf(version)); } } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Getting note : " + note.getTitle()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle())); note.save(); } } else { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response")); } in.close(); conn.disconnect(); mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK")); } catch (MalformedURLException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } } else { mSyncRunning = false; EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:com.hly.component.download.DownloadTransaction.java
public HttpURLConnection getHttpConnetion(String url) throws IOException { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("GET"); return connection; }
From source file:org.devnexus.aerogear.HttpRestProvider.java
private HttpURLConnection prepareConnection(String id) { HttpURLConnection connection = connectionPreparer.get(id); connection.setReadTimeout(timeout);/*from www .j a v a 2 s .co m*/ connection.setConnectTimeout(timeout); return connection; }
From source file:ir.rasen.charsoo.controller.image_loader.core.download.BaseImageDownloader.java
/** * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL * * @param url URL to connect to// w w w. j a v a2 s .co m * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable. * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected HttpURLConnection createConnection(String url, Object extra) throws IOException { String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS); HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); return conn; }
From source file:com.yahoo.druid.hadoop.DruidHelper.java
protected List<DataSegment> getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) { String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action"; logger.info("Sending request to overlord at " + urlStr); String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString()); logger.info("request json is " + requestJson); int numTries = 3; //TODO: should be configurable? for (int trial = 0; trial < numTries; trial++) { try {/*from ww w . java 2 s .c o m*/ logger.info("attempt number {} to get list of segments from overlord", trial); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("content-type", "application/json"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setConnectTimeout(60000); //TODO: 60 secs, shud be configurable? OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes()); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { ObjectMapper mapper = DruidInitialization.getInstance().getObjectMapper(); Map<String, Object> obj = mapper.readValue(conn.getInputStream(), new TypeReference<Map<String, Object>>() { }); return mapper.convertValue(obj.get("result"), new TypeReference<List<DataSegment>>() { }); } else { logger.warn( "Attempt Failed to get list of segments from overlord. response code {} , response {}", responseCode, IOUtils.toString(conn.getInputStream())); } } catch (Exception ex) { logger.warn("Exception in getting list of segments from overlord", ex); } try { Thread.sleep(5000); //wait before next trial } catch (InterruptedException ex) { Throwables.propagate(ex); } } throw new RuntimeException( String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]", dataSource, interval, overlordUrl)); }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * * @param urlStr// w ww . j a v a 2 s . c om * the URL String * @param requestMethod * Method type * @param params * Parameters to pass in request * @param header * Header parameters * @param inputStream * Input stream of image * @param fileName * Image file name * @param fileParamName * Image Filename parameter. It requires in some provider. * @return Response object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final Map<String, String> params, final Map<String, String> header, final InputStream inputStream, final String fileName, final String fileParamName, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (requestMethod.equalsIgnoreCase(MethodType.POST.toString()) || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (inputStream != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { LOG.debug(requestMethod + " request"); String boundary = "----Socialauth-posting" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); write(out, boundary + "\r\n"); if (fileParamName != null) { write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + fileName + "\"\r\n"); } else { write(out, "Content-Disposition: form-data; filename=\"" + fileName + "\"\r\n"); } write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n"); int b; while ((b = inputStream.read()) != -1) { out.write(b); } // out.write(imageFile); write(out, "\r\n"); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); // write(out, // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n"); LOG.debug(entry.getValue()); out.write(entry.getValue().getBytes("UTF-8")); write(out, "\r\n"); } write(out, boundary + "--\r\n"); write(out, "\r\n"); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }