List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:to.noc.devicefp.server.service.MaxMindServiceImpl.java
private MaxMindLocation createFromWebService(String ip) { MaxMindLocation location = null;//from w ww . j av a 2 s. c o m try { URL url = new URL("http://geoip.maxmind.com/e?l=" + maxMindLicenseKey + "&i=" + ip); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setConnectTimeout(10 * 1000); // 10 seconds BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO-8859-1")); String resultsLine = r.readLine(); connection.disconnect(); if (resultsLine != null) { // Split on a comma only if it has zero or an even number of quotes // after it. Assumes quotes are never escaped. String values[] = resultsLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); location = new MaxMindLocation(); location.setIpAddress(ip); location.setStamp(new Date()); for (GeoIpField field : GeoIpField.values()) { if (field.ordinal() >= values.length) { break; } String val = values[field.ordinal()]; // replace leading and trailing whitespace and quotes val = val.replaceAll("^\"?\\s*|\\s*\"?$", ""); if (!val.isEmpty()) { addLocationField(location, field, val); } } } } catch (Exception ex) { log.error("", ex); location = null; } return location; }
From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * //from www.jav a2 s .com * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(final URL url, final Request<?> request) throws IOException { final HttpURLConnection connection = createConnection(url); final int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection and optional settings * for the connection// w w w. j ava 2s .c o m * * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @param connectionSettings * The connection settings to apply * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header, 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 (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { 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 (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:utils.httpUtil_inThread.java
/** * ?(?)/*from w w w . jav a 2 s . c om*/ * * @return ?null? */ public byte[] HttpGetBitmap(String url, String cookie, int timeout_connection, int timeout_read) { byte[] bytes = null; InputStream is = null; try { //?? if (timeout_connection <= 1000) timeout_connection = timeout_pic_connection; if (timeout_read < 1000) timeout_read = timeout_pic_read; URL bitmapURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) bitmapURL.openConnection(); if (cookie != null && !cookie.equals("")) conn.setRequestProperty("Cookie", cookie); //cookie conn.setConnectTimeout(timeout_connection); conn.setReadTimeout(timeout_read); conn.setDoInput(true); conn.connect(); //? is = conn.getInputStream(); bytes = InputStreamUtils.InputStreamTOByte(is); } catch (Exception e) { abstract_LogUtil.e(this, "[]" + e.toString()); } finally { try { if (is != null) is.close(); } catch (Exception e) { abstract_LogUtil.e(this, "[InputStream]"); } } return bytes; }
From source file:de.steveliedtke.calendar.domain.impl.EventServiceImpl.java
private String fetchCalendarUrl(String urlToRead) { URL url;//from w ww. j av a 2s. c o m HttpURLConnection conn; BufferedReader rd; String line; String result = ""; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(60000); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result += line; } rd.close(); } catch (Exception e) { logger.warning(e.getMessage()); } return result; }
From source file:com.starit.diamond.server.service.NotifyService.java
/** * http get//from ww w .jav a 2s .com * * @param urlString * @return */ private String invokeURL(String urlString) { HttpURLConnection conn = null; URL url = null; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); conn.connect(); InputStream urlStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(urlStream)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) reader.close(); } return sb.toString(); } catch (Exception e) { // TODO log.error("http,url=" + urlString, e); } finally { if (conn != null) { conn.disconnect(); } } return "error"; }
From source file:com.mtt.myapp.home.service.HomeService.java
/** * Get panel entries containing the entries from the given RSS * url.//w w w.j a v a2s .c o m * * @param feedURL rss url message * @param maxSize max size * @param includeReply if including reply * @return {@link PanelEntry} list */ public List<PanelEntry> getPanelEntries(String feedURL, int maxSize, boolean includeReply) { SyndFeedInput input = new SyndFeedInput(); XmlReader reader = null; HttpURLConnection feedConnection = null; try { List<PanelEntry> panelEntries = new ArrayList<PanelEntry>(); URL url = new URL(feedURL); feedConnection = (HttpURLConnection) url.openConnection(); feedConnection.setConnectTimeout(4000); feedConnection.setReadTimeout(4000); reader = new XmlReader(feedConnection); SyndFeed feed = input.build(reader); int count = 0; for (Object eachObj : feed.getEntries()) { SyndEntryImpl each = cast(eachObj); if (!includeReply && StringUtils.startsWithIgnoreCase(each.getTitle(), "Re: ")) { continue; } if (count++ > maxSize) { break; } PanelEntry entry = new PanelEntry(); entry.setAuthor(each.getAuthor()); entry.setLastUpdatedDate( each.getUpdatedDate() == null ? each.getPublishedDate() : each.getUpdatedDate()); entry.setTitle(each.getTitle()); entry.setLink(each.getLink()); panelEntries.add(entry); } Collections.sort(panelEntries); return panelEntries; } catch (Exception e) { LOG.error("Error while patching the feed entries for {} : {}", feedURL, e.getMessage()); } finally { if (feedConnection != null) { feedConnection.disconnect(); } IOUtils.closeQuietly(reader); } return Collections.emptyList(); }
From source file:com.wisc.cs407project.ImageLoader.ImageLoader.java
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); Bitmap b = decodeFile(f);// www . j a v a2s .co m //from Local Directory BufferedReader in = null; UrlValidator validator = new UrlValidator(); if (new File(url).exists()) { b = decodeFile(new File(url)); if (b != null) return b; } //from web try { //check SD cache first if (b != null) return b; Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];// w w w . j a v a 2 s. co m Course dm = (Course) payload.getData().get(0); DownloadProgress dp = new DownloadProgress(); try { HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = client.createUrlWithCredentials(dm.getDownloadUrl()); Log.d(TAG, "Downloading:" + url); URL u = new URL(url); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip"; dp.setMessage(localFileName); dp.setProgress(0); publishProgress(dp); Log.d(TAG, "saving to: " + localFileName); FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName)); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); dp.setMessage(ctx.getString(R.string.download_complete)); publishProgress(dp); payload.setResult(true); } catch (ClientProtocolException cpe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(cpe); } else { cpe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (SocketTimeoutException ste) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ste); } else { ste.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException ioe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ioe); } else { ioe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } return payload; }
From source file:com.mabi87.httprequestbuilder.HTTPRequest.java
/** * @throws IOException/* w w w.j a v a 2s . c o m*/ * throws from HttpURLConnection method. * @return the HTTPResponse object */ private HTTPResponse get() throws IOException { URL url = null; if (mParameters.size() > 0) { url = new URL(mPath + "?" + getQuery(mParameters)); } else { url = new URL(mPath); } HttpURLConnection lConnection = (HttpURLConnection) url.openConnection(); lConnection.setReadTimeout(mReadTimeoutMillis); lConnection.setConnectTimeout(mConnectTimeoutMillis); lConnection.setRequestMethod("GET"); lConnection.setDoInput(true); HTTPResponse response = readPage(lConnection); return response; }