List of usage examples for java.net URLConnection getHeaderField
public String getHeaderField(int n)
From source file:anhttpserver.ServerTest.java
@Test public void multiThreadContextIsolationTest() throws Exception { final String res1 = "1111111111"; final String res2 = "1"; final String TEST_HEADER = "TEST-HEADER"; final AtomicBoolean testPassed = new AtomicBoolean(true); class ThreadTestHttpHandlerAdapter extends ByteArrayHandlerAdapter { private String result; private int timeToSleep; ThreadTestHttpHandlerAdapter(String result, int timeToSleep) { this.result = result; this.timeToSleep = timeToSleep; }//w w w . j av a 2 s . c om @Override public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) throws IOException { setResponseHeader(TEST_HEADER, result, httpRequestContext); try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { throw new RuntimeException(e); } return result.getBytes(); } } class ThreadTester implements Runnable { private String url; private String result; private int repeatCount; ThreadTester(String url, String result, int repeatCount) { this.url = url; this.result = result; this.repeatCount = repeatCount; } public void run() { try { for (int i = 0; i < repeatCount; i++) { if (!testPassed.get()) { return; } URLConnection connection = getConnection(url); String headerValue = connection.getHeaderField(TEST_HEADER); if (!headerValue.equals(result)) { testPassed.set(false); return; } if (!getResult(connection).equals(result)) { testPassed.set(false); return; } } } catch (Exception e) { testPassed.set(false); } } } server.addHandler("/thread1", new ThreadTestHttpHandlerAdapter(res1, 0)); server.addHandler("/thread2", new ThreadTestHttpHandlerAdapter(res2, 1)); int count = 50; Thread[] threads = new Thread[count]; String url1 = "http://localhost:9999/thread1"; String url2 = "http://localhost:9999/thread2"; for (int i = 0; i < count; i++) { threads[i] = new Thread(new ThreadTester(i % 2 == 0 ? url1 : url2, i % 2 == 0 ? res1 : res2, 20)); threads[i].start(); } for (int i = 0; i < count; i++) { threads[i].join(); } assertTrue(testPassed.get()); }
From source file:org.openhab.ui.habpanel.internal.gallery.community.CommunityWidgetGalleryProvider.java
@Override public GalleryWidgetsItem getGalleryItem(String id) throws Exception { if (Integer.parseInt(id) < 1) { throw new IllegalArgumentException("invalid community gallery id"); }/*from w w w . j ava2 s . c om*/ URL url = new URL(String.format("%s%s.json", COMMUNITY_TOPIC_URL, id)); URLConnection connection = url.openConnection(); try { Reader reader = new InputStreamReader(connection.getInputStream()); DiscourseTopicResponse parsed = gson.fromJson(reader, DiscourseTopicResponse.class); GalleryWidgetsItem item = new GalleryWidgetsItem(); item.id = id; item.title = parsed.title; item.description = parsed.post_stream.posts[0].cooked; item.author = parsed.details.created_by.username; item.authorName = parsed.post_stream.posts[0].display_username; item.authorAvatarUrl = COMMUNITY_BASE_URL + parsed.details.created_by.avatar_template; item.createdDate = parsed.created_at; item.likes = parsed.like_count; item.views = parsed.views; item.posts = parsed.posts_count; item.widgets = new ArrayList<GalleryWidgetAttachment>(); if (parsed.post_stream.posts[0].link_counts != null) { for (DiscoursePostLink link : parsed.post_stream.posts[0].link_counts) { if (link.url.startsWith("https://github.com")) { item.githubLink = String.join("/", Arrays.asList(link.url.split("/", 6)).subList(0, 5)); } else if (link.url.endsWith(".json")) { GalleryWidgetAttachment widget = new GalleryWidgetAttachment(); if (link.url.startsWith("//")) { link.url = "https:" + link.url; } widget.sourceUrl = link.url; URL widgetUrl = new URL(link.url); URLConnection widgetDownload = widgetUrl.openConnection(); try { widget.contents = IOUtils.toString(widgetDownload.getInputStream()); String cDisp = widgetDownload.getHeaderField("Content-Disposition"); if (cDisp != null && cDisp.indexOf("=") != -1 && cDisp.indexOf(".widget.json") != -1) { widget.id = cDisp.split("=")[1].replaceAll("\"", "").replaceAll("]", "") .replaceAll(".widget.json", ""); item.widgets.add(widget); } } finally { IOUtils.closeQuietly(widgetDownload.getInputStream()); } } } } return item; } finally { IOUtils.closeQuietly(connection.getInputStream()); } }
From source file:com.juick.android.Utils.java
public static BINResponse getBinary(Context context, final String url, final Notification progressNotification, int timeout) { try {//ww w . j a va 2 s .c om if (url == null) return new BINResponse("NULL url", false, null); URLConnection urlConnection = new URL(url).openConnection(); InputStream inputStream = urlConnection.getInputStream(); BINResponse binResponse = streamToByteArray(inputStream, progressNotification); inputStream.close(); String location = urlConnection.getHeaderField("Location"); if (location != null) { return getBinary(context, location, progressNotification, timeout); } return binResponse; } catch (Exception e) { if (progressNotification instanceof DownloadErrorNotification) { ((DownloadErrorNotification) progressNotification) .notifyDownloadError("HTTP connect: " + e.toString()); } Log.e("getBinary", e.toString()); return new BINResponse(e.toString(), true, null); } }
From source file:org.lockss.util.UrlUtil.java
/** * Return a list of header fields (in the format "key;fieldValue") for conn * @param conn URLConnection to get headers from * @return list of header fields (in the format "key;fieldValue") for conn * @throws IllegalArgumentException if a null conn is supplied */// w w w . j ava2 s . c o m public static List getHeaders(URLConnection conn) { if (conn == null) { throw new IllegalArgumentException("Called with null URLConnection"); } List returnList = new ArrayList(); boolean done = false; for (int ix = 0; !done; ix++) { String headerField = conn.getHeaderField(ix); String headerFieldKey = conn.getHeaderFieldKey(ix); done = (headerField == null && headerFieldKey == null); if (!done) { returnList.add(headerFieldKey + ";" + headerField); } } return returnList; }
From source file:deincraftlauncher.IO.download.Downloader.java
public void prepare() { //generating: fileName, totalSize, preparing = true;//w w w .j av a2 s . co m prepareThread = new Thread() { @Override public void run() { try { target = new URL(link); URLConnection targetCon = target.openConnection(); totalSize = targetCon.getContentLength(); String raw = targetCon.getHeaderField("Content-Disposition"); if (raw != null && raw.contains("=")) { fileName = raw.split("=")[1]; fileName = fileName.split(";")[0]; } else { fileName = "Unbekannt"; } fileName = fileName.replaceAll("\"", ""); System.out.println("Prepared Download: size: " + totalSize + " name=" + fileName); prepared = true; preparing = false; onPrepared.call(instance); } catch (MalformedURLException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } } }; prepareThread.start(); }
From source file:org.holistic.ws_proxy.WSProxyHelper.java
private void headers_endpoint2client(HttpServletResponse resp, URLConnection objURLConn) throws Exception { int m_iHeaderNumber = 1; String m_sHeaderName = objURLConn.getHeaderFieldKey(m_iHeaderNumber); for (String m_sHeaderValue = objURLConn.getHeaderField(m_iHeaderNumber); m_sHeaderName != null && m_sHeaderValue != null; m_sHeaderValue = objURLConn.getHeaderField(m_iHeaderNumber)) { if (m_sHeaderName.equalsIgnoreCase("Set-Cookie")) { String m_sCookie = objURLConn.getHeaderField(m_iHeaderNumber); if (m_sCookie != null && !m_sCookie.equals("")) { log.debug("EndPoint Cookie: " + m_sCookie); int m_posicion = m_sCookie.indexOf("="); String m_sCookieModificada = m_sCookie.substring(0, m_posicion) + EXTRA_COOKIE + m_sCookie.substring(m_posicion); log.debug("Al cliente le transmito la cookie modificada: " + m_sCookieModificada); resp.addHeader("Set-Cookie", m_sCookieModificada); }//from w ww .j a v a 2 s .c o m } else if (!m_sHeaderName.equalsIgnoreCase("Content-Length") && !m_sHeaderName.equalsIgnoreCase("Transfer-Encoding")) { if (m_sHeaderName.equalsIgnoreCase("Cache-Control") && m_sHeaderValue.equalsIgnoreCase("max-age=43200")) { //resp.addHeader(m_sHeaderName, "post-check=43200, pre-check=3600"); //resp.addHeader(m_sHeaderName, "post-check=300, pre-check=420, must-revalidate"); resp.addHeader(m_sHeaderName, "post-check=600, pre-check=601"); } else { resp.addHeader(m_sHeaderName, m_sHeaderValue); log.debug("EndPointToClient HEADER[" + m_sHeaderName + "] - VALUE[" + m_sHeaderValue + "]"); } } m_iHeaderNumber++; m_sHeaderName = objURLConn.getHeaderFieldKey(m_iHeaderNumber); } }
From source file:org.apache.jmeter.protocol.http.control.CacheManager.java
private boolean hasVaryHeader(URLConnection conn) { return conn.getHeaderField(HTTPConstants.VARY) != null; }
From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java
protected Charset getCharset(final URLConnection urlConnection) { Charset charset = null;/*from w ww . jav a2 s . co m*/ // Prio 1: content encoding specified in header String encoding = urlConnection.getContentEncoding(); // Prio 2: charset specified within content type (specified in header) if (encoding == null) { final String contentType = urlConnection.getHeaderField("Content-Type"); if (contentType != null) { for (final String metaTagParameter : contentType.replace(" ", "").split(";")) { if (metaTagParameter.startsWith("charset=")) { encoding = metaTagParameter.split("=", 2)[1]; break; } } } } // Prio 3: default charset if (encoding == null) { return Charset.defaultCharset(); } // Create charset try { charset = Charset.forName(encoding); } catch (final Exception ex) { LOG.warn("Unsupported encoding " + encoding + " by " + urlConnection.getURL().toExternalForm(), ex); } // Fallback if (charset == null) { charset = Charset.defaultCharset(); } // Done return charset; }
From source file:org.callimachusproject.xml.InputSourceResolver.java
/** * returns null for 404 resources./*from w w w . j av a 2s .c o m*/ */ private InputSource resolveURL(String systemId) throws IOException { URLConnection con = new URL(systemId).openConnection(); con.addRequestProperty("Accept", getAcceptHeader()); con.addRequestProperty("Accept-Encoding", "gzip"); try { String base = con.getURL().toExternalForm(); String type = con.getContentType(); String encoding = con.getHeaderField("Content-Encoding"); InputStream in = con.getInputStream(); if (encoding != null && encoding.contains("gzip")) { in = new GZIPInputStream(in); } return create(type, in, base); } catch (FileNotFoundException e) { return null; } catch (IOException e) { logger.warn("Could not resolve {}", systemId); throw e; } }
From source file:eionet.cr.staging.FileDownloader.java
/** * Derives a name for the file to be downloaded from the given {@link URLConnection}. * * @param connection The given {@link URLConnection}. * @return The derived file name.//from ww w .ja v a 2 s. c o m */ private String getFileName(URLConnection connection) { // If file name already given, just return it. if (StringUtils.isNotBlank(newFileName)) { return newFileName; } // Attempt detection from the response's "Content-Disposition" header. String contentDisposition = connection.getHeaderField("Content-Disposition"); if (StringUtils.isNotBlank(contentDisposition)) { String s = StringUtils.substringAfter(contentDisposition, "filename"); if (StringUtils.isNotBlank(s)) { s = StringUtils.substringAfter(s, "="); if (StringUtils.isNotBlank(s)) { s = StringUtils.substringAfter(s, "\""); if (StringUtils.isNotBlank(s)) { s = StringUtils.substringBefore(s, "\""); if (StringUtils.isNotBlank(s)) { return s.trim(); } } } } } // // Attempt detection from the response's "Content-Location" header. // String contentLocation = connection.getHeaderField("Content-Location"); // if (StringUtils.isNotBlank(contentLocation)) { // String s = new File(contentLocation).getName(); // if (StringUtils.isNotBlank(s)) { // return s.trim(); // } // } // // Attempt detection from the URL itself. String s = StringUtils.substringAfterLast(connection.getURL().toString(), "#"); if (StringUtils.isBlank(s)) { s = StringUtils.substringAfterLast(connection.getURL().toString(), "/"); } if (StringUtils.isNotBlank(s)) { // Remove all characters that are not one of these: a latin letter, a digit, a minus, a dot, an underscore. s = s.replaceAll("[^a-zA-Z0-9-._]+", ""); } // If still no success, then just generate a hash from the URL. return StringUtils.isBlank(s) ? DigestUtils.md5Hex(connection.getURL().toString()) : s; }