List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a unknown user/* w w w . j a va2s . c om*/ * * @throws Exception error */ @Test public void test02RequestUnknownUser() throws Exception { log.trace(">test02RequestUnknownUser()"); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write("user=reqtestunknown&password=foo123&keylength=2048".getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } log.info("Content-Type: " + con.getContentType()); boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); log.info(errormsg); String expectedErrormsg = "Username: reqtestunknown\nNon existent username. To generate a certificate a valid username and password must be supplied.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.trace("<test02RequestUnknownUser()"); }
From source file:ORG.oclc.os.SRW.SRUServerTester.java
public String sruRead(String initialURL) { out('\n');/* w w w .j a v a 2s .c om*/ out(" trying: "); out(initialURL); out('\n'); numTests++; URL url; try { url = new URL(initialURL); } catch (java.net.MalformedURLException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } HttpURLConnection huc; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentType = huc.getContentType(); if (contentType == null || (!contentType.contains("text/xml") && !contentType.contains("application/xml"))) { out(" ** Warning: Content-Type not set to text/xml or application/xml"); out('\n'); out(" Content-type: "); out(contentType); out('\n'); numWarns++; } InputStream urlStream; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: opening URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine; StringBuilder content = new StringBuilder(); Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading first line of response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine == null) { out("</pre><pre class='red'>"); out("test failed: No input read from URL"); out('\n'); out("</pre><pre>"); 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(); // I ran into a server that put an empty line before the stylesheet reference while (inputLine.length() == 0) inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine.startsWith("<?xml-stylesheet ")) { href = (inputLine.substring(inputLine.indexOf("href=") + 6)); href = href.substring(0, href.indexOf('"')); transformer = transformers.get(href); if (stylesheets.get(href) == null) try { // never seen this stylesheet before out(" reading stylesheet: "); out(href); out('\n'); out(" from source: "); out(url.toString()); out('\n'); StreamSource source = new StreamSource(url.toString()); TransformerFactory tFactory = TransformerFactory.newInstance(); Source stylesht = tFactory.getAssociatedStylesheet(source, null, null, null); transformer = tFactory.newTransformer(stylesht); transformers.put(href, transformer); } catch (TransformerConfigurationException e) { log.error(e, e); out("</pre><pre class='red'>"); out("unable to load stylesheet: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); } stylesheets.put(href, href); } else content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } // if(!xml) { // out("test failed: response was not an XML record");out('\n'); // out(content.toString());out('\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)); out(" successfully applied stylesheet '"); out(href); out("'"); out('\n'); } catch (javax.xml.transform.TransformerException e) { out("</pre><pre class='red'>"); out("unable to apply stylesheet '"); out(href); out("'to response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); log.error(e, e); transformer.reset(); } transformer.reset(); } return contentStr; }
From source file:org.wandora.application.gui.OccurrenceTableSingleType.java
@Override public void downloadURLOccurrence() { try {//from www .ja v a 2 s .c om Point p = getTableModelPoint(); if (p != null) { String occurrence = topic.getData(type, langs[p.y]); if (occurrence != null) { occurrence = occurrence.trim(); if (occurrence.length() > 0) { try { URL url = new URL(occurrence); int a = WandoraOptionPane.showConfirmDialog(wandora, "Make data-url instead of text occurrence?", "Make data-url", WandoraOptionPane.INFORMATION_MESSAGE); if (a == WandoraOptionPane.YES_OPTION) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); String contentType = connection.getContentType(); connection.disconnect(); InputStream is = url.openStream(); byte[] dataBytes = IOUtils.toByteArray(is); DataURL dataURL = new DataURL(contentType, dataBytes); topic.setData(type, langs[p.y], dataURL.toExternalForm()); } else { String occurrenceContent = IObox.doUrl(url); topic.setData(type, langs[p.y], occurrenceContent); } } catch (MalformedURLException mue) { WandoraOptionPane.showMessageDialog(wandora, "The occurrence is invalid URL. Can't download.", "Invalid URL exception", WandoraOptionPane.ERROR_MESSAGE); } catch (IOException ioe) { WandoraOptionPane.showMessageDialog( wandora, "Can't read the occurrence URL. IOException occurred ('" + ioe.getMessage() + "').", "Can't read the URL", WandoraOptionPane.ERROR_MESSAGE); } catch (TopicMapException tme) { WandoraOptionPane.showMessageDialog(wandora, "Can't set the occurrence because of a topic map exception. Topic map doesn't function as intended", "Topic map exception occurred", WandoraOptionPane.ERROR_MESSAGE); } catch (Exception e) { WandoraOptionPane.showMessageDialog(wandora, "Exception '" + e.getMessage() + "' occurred while downloading URL '" + occurrence + "'.", "Error downloading URL", WandoraOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } } } } catch (Exception e) { if (wandora != null) wandora.handleError(e); } }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a wrong password/*ww w . j a v a2 s. c o m*/ * * @throws Exception error */ @Test public void test03RequestWrongPwd() throws Exception { log.trace(">test03RequestWrongPwd()"); setupUser(SecConst.TOKEN_SOFT_P12); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong username or password"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test03RequestWrongPwd()"); }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request with wrong status/*from ww w. j av a2 s .com*/ * * @throws Exception error */ @Test public void test04RequestWrongStatus() throws Exception { log.trace(">test04RequestWrongStatus()"); setupUser(SecConst.TOKEN_SOFT_P12); setupUserStatus(EndEntityConstants.STATUS_GENERATED); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong user status! To generate a certificate for a user the user must have status New, Failed or In process.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test04RequestWrongStatus()"); }
From source file:org.ocelotds.integration.AbstractOcelotTest.java
/** * Rcupere la resource via un HttpConnection * * @param resource//from w w w . j a v a2 s.c om * @return * @throws MalformedURLException * @throws IOException */ protected HttpURLConnection getConnectionForResource(String resource) throws MalformedURLException, IOException { StringBuilder sb = new StringBuilder("http://localhost:"); sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append(resource); URL url = new URL(sb.toString()); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); // Authenticator.setDefault(new Authenticator() { // @Override // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("demo", "demo".toCharArray()); // } // }); // ou // String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary("demo:demo".getBytes()); // System.out.println(basicAuth); // uc.setRequestProperty("Authorization", basicAuth); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Date: " + new Date(uc.getDate())); System.out.println("Last modified: " + new Date(uc.getLastModified())); System.out.println("Expiration date: " + new Date(uc.getExpiration())); System.out.println("Response code: " + uc.getResponseCode()); assertThat(uc.getResponseCode()).isEqualTo(200).as("'%s' is unreachable", sb); return uc; }
From source file:blueprint.sdk.google.gcm.GcmSender.java
/** * decodes response from GCM/*from w w w . jav a 2 s .c o m*/ * * @param http HTTP connection * @return response from GCM * @throws IOException */ @SuppressWarnings("ResultOfMethodCallIgnored") private GcmResponse decodeResponse(HttpURLConnection http) throws IOException { GcmResponse result = new GcmResponse(); result.code = getResponseCode(http); if (result.code == HttpURLConnection.HTTP_OK) { try { Response response = mapper.readValue((InputStream) http.getContent(), Response.class); result.multicastId = response.multicast_id; result.success = response.success; result.failure = response.failure; result.canonicalIds = response.canonical_ids; // decode 'results' for (Map<String, String> item : response.results) { GcmResponseDetail detail = new GcmResponseDetail(); if (item.containsKey("message_id")) { detail.success = true; detail.message = item.get("message_id"); } else { detail.success = false; detail.message = item.get("error"); } result.results.add(detail); } } catch (Exception e) { result.code = GcmResponse.ERR_JSON_BIND; L.warn("Can't bind json", e); } } else if (result.code == GcmResponse.ERR_NOT_JSON) { int contentLength = http.getContentLength(); String contentType = http.getContentType(); InputStream ins = (InputStream) http.getContent(); byte[] buffer = new byte[contentLength]; ins.read(buffer); L.warn("response message is not a json. content-type=" + contentType + ", content=" + new String(buffer)); } return result; }
From source file:net.subclient.subsonic.SubsonicConnection.java
/** * Performs a connection to the server executing specified method and passing provided parameters. * @param method One of the supported methods * @param parameters Parametters to be passed to server * @param isJson Defines if JSON is expected. It won't be JSON on any method returning binary contents * @return The performed HTTP connection InputStream * @throws IOException//from w w w. ja va 2 s . c om * @throws InvalidResponseException If the Subsonic servers returns a non parseable response * @throws HTTPException If the server response code is other than 200 * @throws CompatibilityException */ private InputStream connect(ApiMethod method, List<HttpParameter> parameters, boolean isJson) throws IOException, InvalidResponseException, HTTPException, CompatibilityException { // Generate URL object URL url = new URL(this.serverURL.toString() + method.toString()); // Append version param to parameters array parameters.add(new HttpParameter("v", this.getVersionCompatible(method.getVersion()).toString(true))); // Open HTTP/HTTPS Connection HttpURLConnection conn = (this.isSSL) ? (HttpsURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Add parameters to be sent OutputStreamWriter connOut = new OutputStreamWriter(conn.getOutputStream()); StringBuilder auxParams = new StringBuilder(this.parametersString); for (HttpParameter parameter : parameters) auxParams.append(String.format("&%s", parameter.toString())); //Send parameters to outer connection connOut.write(auxParams.toString()); connOut.flush(); connOut.close(); // Check the response code is 200 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) throw new HTTPException(conn.getResponseCode()); // Check the content type is application/json if (isJson && conn.getContentType().indexOf(JSON_CONTENT_TYPE) == -1) throw new InvalidResponseException(conn.getContentType()); // Return the connection InputStream return conn.getInputStream(); }
From source file:com.moviejukebox.plugin.SratimPlugin.java
public boolean downloadSubtitleZip(Movie movie, String subDownloadLink, File subtitleFile, boolean bluray) { @SuppressWarnings("resource") OutputStream fileOutputStream = null; HttpURLConnection connection = null; boolean found = false; try {/* w ww . ja va 2 s . c o m*/ URL url = new URL(subDownloadLink); connection = (HttpURLConnection) (url.openConnection(YamjHttpClientBuilder.getProxy())); String contentType = connection.getContentType(); LOG.debug("contentType: {}", contentType); // Check that the content is zip and that the site did not blocked the download if (!"application/octet-stream".equals(contentType)) { LOG.error( "********** Error - Sratim subtitle download limit may have been reached. Suspending subtitle download."); subtitleDownload = false; return false; } Collection<MovieFile> parts = movie.getMovieFiles(); Iterator<MovieFile> partsIter = parts.iterator(); byte[] buf = new byte[1024]; try (InputStream inputStream = connection.getInputStream(); ZipInputStream zipInputStream = new ZipInputStream(inputStream)) { ZipEntry zipentry = zipInputStream.getNextEntry(); while (zipentry != null) { // for each entry to be extracted String entryName = zipentry.getName(); LOG.debug("ZIP entryname: {}", entryName); // Check if this is a subtitle file if (entryName.toUpperCase().endsWith(".SRT") || entryName.toUpperCase().endsWith(".SUB")) { int n; String entryExt = entryName.substring(entryName.lastIndexOf('.')); if (movie.isTVShow()) { // for tv show, use the subtitleFile parameter because tv show is // handled by downloading subtitle from the episode page (each episode for its own) fileOutputStream = FileTools.createFileOutputStream(subtitleFile + entryExt); } else { // for movie, we need to save all subtitles entries // from inside the zip file, and name them according to // the movie file parts. if (partsIter.hasNext()) { MovieFile moviePart = partsIter.next(); String partName = moviePart.getFile().getAbsolutePath(); if (bluray) { // This is a BDRip, should be saved as index.EXT under BDMV dir to match PCH requirments partName = partName.substring(0, partName.lastIndexOf("BDMV")) + "BDMV\\index"; } else { partName = partName.substring(0, partName.lastIndexOf('.')); } fileOutputStream = FileTools.createFileOutputStream(partName + entryExt); } else { // in case of some mismatch, use the old code fileOutputStream = FileTools.createFileOutputStream(subtitleFile + entryExt); } } while ((n = zipInputStream.read(buf, 0, 1024)) > -1) { fileOutputStream.write(buf, 0, n); } found = true; } zipInputStream.closeEntry(); zipentry = zipInputStream.getNextEntry(); } } } catch (IOException error) { LOG.error("Error - {}", error.getMessage()); return false; } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { // Ignore } if (connection != null) { connection.disconnect(); } } return found; }
From source file:com.wordpress.metaphorm.authProxy.hook.AuthProxyServletFilter.java
private boolean processLocalLiferayResourceRequest(HttpServletRequest servletReq, HttpServletResponse servletResp) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, MalformedURLException, UnsupportedEncodingException { OAuthState oAuthState = OAuthStateManager.getOAuthState(servletReq.getSession().getId()); String url = servletReq.getRequestURL().toString(); String queryString = servletReq.getQueryString(); if (oAuthState != null) { _log.debug("Requesting local Liferay resource using p_auth from OAuthState object!"); try {/*from ww w .j a va 2s .co m*/ if (queryString != null) queryString += "&p_auth=" + oAuthState.getPAuth(); else queryString = "p_auth=" + oAuthState.getPAuth(); } catch (ExpiredStateException e) { _log.debug("Could not provide p_auth parameter enrichment"); } } _log.debug("Requesting " + url + (queryString != null ? "?" + queryString : "")); HttpURLConnection uRLConn = (HttpURLConnection) new URL( url + (queryString != null ? "?" + queryString : "")).openConnection(); uRLConn.addRequestProperty("User-Agent", PROXY_USER_AGENT); uRLConn.addRequestProperty("Cookie", "JSESSIONID=" + servletReq.getSession().getId()); String transformHeader = servletReq.getHeader("transform-response-to"); if (transformHeader == null) transformHeader = servletReq.getParameter("transform-response-to"); uRLConn.connect(); int httpStatusCode = uRLConn.getResponseCode(); servletResp.setStatus(httpStatusCode); if (httpStatusCode < 200 || httpStatusCode >= 300) { // Return immediately for error codes return true; } InputStream in = uRLConn.getInputStream(); if (transformHeader != null) { _log.debug("Transforming JSON to XML"); servletResp.setContentType("application/xml"); String json = sinkInputStream(in, servletResp.getCharacterEncoding()); Utils.writeJSONAsXML(json, servletResp.getWriter()); } else { // Proxy content type hearder servletResp.setContentType(uRLConn.getContentType()); OutputStream out = servletResp.getOutputStream(); int i; while ((i = in.read()) != -1) { out.write((byte) i); } } return true; }