List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.wso2.extension.siddhi.store.rdbms.test.osgi.util.TestUtil.java
public static HTTPResponseMessage sendHRequest(String body, URI baseURI, String path, String contentType, String methodType, Boolean auth, String userName, String password) { try {//from ww w . j a v a 2 s .c o m HttpURLConnection urlConn = null; try { urlConn = TestUtil.generateRequest(baseURI, path, methodType, false); } catch (IOException e) { TestUtil.handleException("IOException occurred while running the HttpsSourceTestCaseForSSL", e); } if (auth) { TestUtil.setHeader(urlConn, "Authorization", "Basic " + java.util.Base64.getEncoder().encodeToString((userName + ":" + password).getBytes())); } if (contentType != null) { TestUtil.setHeader(urlConn, "Content-Type", contentType); } TestUtil.setHeader(urlConn, "HTTP_METHOD", methodType); if (methodType.equals(HttpMethod.POST.name()) || methodType.equals(HttpMethod.PUT.name())) { TestUtil.writeContent(urlConn, body); } assert urlConn != null; HTTPResponseMessage httpResponseMessage = new HTTPResponseMessage(urlConn.getResponseCode(), urlConn.getContentType(), urlConn.getResponseMessage()); urlConn.disconnect(); return httpResponseMessage; } catch (IOException e) { TestUtil.handleException("IOException occurred while running the HttpsSourceTestCaseForSSL", e); } return new HTTPResponseMessage(); }
From source file:org.goodev.droidddle.utils.IOUtil.java
public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring) throws OpenUriException { if (uri == null) { throw new IllegalArgumentException("Uri cannot be empty"); }/*from ww w . j av a 2 s.c o m*/ String scheme = uri.getScheme(); if (scheme == null) { throw new OpenUriException(false, new IOException("Uri had no scheme")); } InputStream in = null; if ("content".equals(scheme)) { try { in = context.getContentResolver().openInputStream(uri); } catch (FileNotFoundException | SecurityException e) { throw new OpenUriException(false, e); } } else if ("file".equals(scheme)) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) { AssetManager assetManager = context.getAssets(); StringBuilder assetPath = new StringBuilder(); for (int i = 1; i < segments.size(); i++) { if (i > 1) { assetPath.append("/"); } assetPath.append(segments.get(i)); } try { in = assetManager.open(assetPath.toString()); } catch (IOException e) { throw new OpenUriException(false, e); } } else { try { in = new FileInputStream(new File(uri.getPath())); } catch (FileNotFoundException e) { throw new OpenUriException(false, e); } } } else if ("http".equals(scheme) || "https".equals(scheme)) { OkHttpClient client = new OkHttpClient(); HttpURLConnection conn = null; int responseCode = 0; String responseMessage = null; try { conn = new OkUrlFactory(client).open(new URL(uri.toString())); } catch (MalformedURLException e) { throw new OpenUriException(false, e); } try { conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); conn.setReadTimeout(DEFAULT_READ_TIMEOUT); responseCode = conn.getResponseCode(); responseMessage = conn.getResponseMessage(); if (!(responseCode >= 200 && responseCode < 300)) { throw new IOException("HTTP error response."); } if (reqContentTypeSubstring != null) { String contentType = conn.getContentType(); if (contentType != null && !contentType.contains(reqContentTypeSubstring)) { throw new IOException("HTTP content type '" + contentType + "' didn't match '" + reqContentTypeSubstring + "'."); } } in = conn.getInputStream(); } catch (IOException e) { if (responseCode > 0) { throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e); } else { throw new OpenUriException(false, e); } } } return in; }
From source file:biz.gabrys.lesscss.extended.compiler.source.HttpSource.java
/** * Returns an encoding of the source code. Before the first {@link #getContent()} call returns current source * encoding. After the first {@link #getContent()} call always returns the source encoding read while downloading * the source contents.// w w w .j a v a 2s . c om * @return the encoding. * @since 1.0 */ public String getEncoding() { if (encoding != null) { return encoding; } final HttpURLConnection connection = makeConnection(false); return getEncodingFromContentType(connection.getContentType()); }
From source file:biz.gabrys.lesscss.extended.compiler.source.HttpSource.java
public String getContent() { final HttpURLConnection connection = makeConnection(true); encoding = getEncodingFromContentType(connection.getContentType()); String content;/*from w w w . j av a 2 s.c om*/ try { content = IOUtils.toString(connection.getInputStream(), encoding); } catch (final IOException e) { connection.disconnect(); throw new SourceException(e); } lastModificationDate = getModificationDate(connection.getLastModified()); connection.disconnect(); return content; }
From source file:ar.com.zauber.common.image.impl.JREImageRetriver.java
/** @see ImageRetriver#retrive(URL) */ public final InputStream retrive(final URL url) throws IOException { Validate.notNull(url);//from w w w.ja va2 s. c o m final URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) uc; prepare(uc); huc.connect(); final String contentType = huc.getContentType(); if (contentType != null && contentType.length() > 0 && !huc.getContentType().trim().startsWith("image/")) { throw new RuntimeException("la URL no parece apuntar a una imagen "); } if (huc.getContentLength() > maxBytes) { throw new RuntimeException("la imagen pesa ms de " + maxBytes); } final InputStream is = uc.getInputStream(); return is; } else { throw new IllegalArgumentException("solo se soporta el protocolo " + " http"); } }
From source file:ORG.oclc.os.SRW.Utilities.java
public static String readURL(String urlStr, boolean debug) { if (debug)/*from www . ja v a2s . c o m*/ System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { e.printStackTrace(); System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { // normally, you'd expect to read the next line of input here // but some servers don't put a newline after the initial <?xml ?> int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
From source file:org.gatein.portal.people.test.GateInPeopleTestCase.java
@Test @RunAsClient//from w ww. j a va 2 s. com public void testFindUser() throws Exception { // URL url = deploymentURL.toURI().resolve("embed/PeopleApplication").toURL(); driver.get(url.toString()); URL findUserURL = new URL( url.toString() + "?juzu.op=Controller.findUsers&javax.portlet.id=0&javax.portlet.phase=resource"); HttpURLConnection conn = (HttpURLConnection) findUserURL.openConnection(); conn.connect(); Assert.assertEquals("application/json;charset=UTF-8", conn.getContentType()); Assert.assertEquals(200, conn.getResponseCode()); // BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[256]; for (int l = bis.read(buff); l != -1; l = bis.read(buff)) { baos.write(buff, 0, l); } String response = new String(baos.toByteArray(), "UTF-8"); // JSONObject json = new JSONObject(response); OrganizationService orgService = (OrganizationService) RootContainer.getInstance() .getComponentInstanceOfType(OrganizationService.class); ListAccess<User> listAccess = orgService.getUserHandler().findAllUsers(); Assert.assertEquals(10, listAccess.getSize()); User[] users = listAccess.load(0, 10); for (int i = 0; i < 10; i++) { Assert.assertNotNull(json.get(users[i].getUserName())); } }
From source file:eu.creatingfuture.propeller.webLoader.servlets.WebRequestServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Access-Control-Allow-Origin", "*"); String getUrl = req.getParameter("get"); if (getUrl == null) { resp.sendError(400);//from w ww . j a v a 2 s. c o m return; } logger.info(getUrl); URL url; HttpURLConnection connection = null; try { url = new URL(getUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); resp.setContentType(connection.getContentType()); resp.setContentLengthLong(connection.getContentLengthLong()); logger.log(Level.INFO, "Content length: {0} response code: {1} content type: {2}", new Object[] { connection.getContentLengthLong(), connection.getResponseCode(), connection.getContentType() }); resp.setStatus(connection.getResponseCode()); IOUtils.copy(connection.getInputStream(), resp.getOutputStream()); } catch (IOException ioe) { resp.sendError(500, ioe.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:n3phele.backend.RepoProxy.java
@GET @Path("{id}/redirect/{filename:[/\\w\\.\\%\\+\\-]+}") public Response redirect(@PathParam("id") Long id, @PathParam("filename") String filename, @QueryParam("expires") long expires, @QueryParam("signature") String signature) throws NotFoundException { Repository item = Dao.repository().load(id); log.info("filename=" + filename); UriBuilder result = UriBuilder.fromUri(item.getTarget()); result.path(item.getRoot()).path(filename); if (expires == 0) { try {/*from ww w .j a v a 2 s.c om*/ URL url = CloudStorage.factory().getURL(item, "", filename).toURL(); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); log.info("Access " + filename + " " + connection.getContentType()); StreamingOutput stream = new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { try { ByteStreams.copy(connection.getInputStream(), output); } catch (Exception e) { throw new WebApplicationException(e); } } }; return Response.ok(stream).type(connection.getContentType()).build(); } catch (Exception e) { log.log(Level.INFO, "Access error ", e); throw new NotFoundException(); } } else { if (!checkTemporaryCredential(expires, signature, item.getCredential().decrypt().getSecret(), result.build().toString())) { log.severe("Expired temporary authorization"); throw new NotFoundException(); } ObjectStream stream = CloudStorage.factory().getObject(item, "", filename); log.info("Access " + filename + " " + stream.getContextType()); return Response.ok(stream.getOutputStream()).type(stream.getContextType()).build(); } }
From source file:org.fusesource.cloudmix.agent.webapp.WebappTest.java
public void testGetStatus() throws Exception { String uri = baseURL + "/status"; HttpURLConnection httpConnection = getHttpConnection(uri); httpConnection.connect();//from w w w .j av a 2s . com verifyResponseCode(200, httpConnection); assertEquals("text/html", httpConnection.getContentType()); assertEquals("OK", httpConnection.getResponseMessage()); InputStream in = httpConnection.getInputStream(); assertNotNull(in); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; int i = 0; while ((line = reader.readLine()) != null) { Pattern pattern = Pattern.compile(EXPECTED_STATUS_REGEXP[i]); Matcher matcher = pattern.matcher(line); assertTrue(line + " doesn't match: " + EXPECTED_STATUS_REGEXP[i], matcher.matches()); i++; } }