List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java
@Test @RunAsClient// w w w. java 2 s . com @Ignore public void testCreatePackageFromDRLAsJson(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON); connection.setDoOutput(true); //Send request BufferedReader br = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream("simple_rules2.drl"))); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); while (br.ready()) dos.writeBytes(br.readLine()); dos.flush(); dos.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_JSON, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** * This test tests that the OCSP response for a status unknown contains the header "cache-control" with the value "no-cache, must-revalidate" * /* w ww. j a va 2 s . c o m*/ * @throws Exception */ @Test public void testUnknownStatusCacheControlHeader() throws Exception { // set ocsp configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.UNTIL_NEXT_UPDATE, "1"); this.helper.alterConfig(map); OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1"))); OCSPReq req = gen.build(); String sBaseURL = httpReqPath + '/' + resourceOcsp; String urlEnding = ""; String b64 = new String(Base64.encode(req.getEncoded(), false)); //String urls = URLEncoder.encode(b64, "UTF-8"); // JBoss/Tomcat will not accept escaped '/'-characters by default URL url = new URL(sBaseURL + '/' + b64 + urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != 200) { log.info("URL when request gave unexpected result: " + url.toString() + " Message was: " + con.getResponseMessage()); } assertEquals("Response code did not match. ", 200, con.getResponseCode()); assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); assertNotNull("No Cache-Control in reply.", con.getHeaderField("Cache-Control")); assertEquals("no-cache, must-revalidate", con.getHeaderField("Cache-Control")); // Create a GET request using Nonce extension, in this case we should have no cache-control header gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1"))); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); req = gen.build(); b64 = new String(Base64.encode(req.getEncoded(), false)); url = new URL(sBaseURL + '/' + b64 + urlEnding); con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != 200) { log.info("URL when request gave unexpected result: " + url.toString() + " Message was: " + con.getResponseMessage()); } assertEquals("Response code did not match. ", 200, con.getResponseCode()); assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue().getEncoded(); // Make sure we have a nonce in the response, we should have since we sent one in the request assertNotNull("Response should have nonce since we sent a nonce in the request", noncerep); ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); assertEquals("Response Nonce was not the same as the request Nonce, it must be", "123456789", new String(oct.getOctets())); assertNull( "Cache-Control in reply although we used Nonce in the request. Responses with Nonce should not have a Cache-control header.", con.getHeaderField("Cache-Control")); }
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. * * @param file//from www.j av a 2s . c o m * @return */ protected Response callRESTfulPDP(InputStream is) { Response response = null; HttpURLConnection connection = null; try { // // Open up the connection // connection = (HttpURLConnection) this.restURL.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); // // Send the request // try (OutputStream os = connection.getOutputStream()) { IOUtils.copy(is, os); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 200) { // // Read the response // ContentType contentType = null; try { contentType = ContentType.parse(connection.getContentType()); if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { response = JSONResponse.load(connection.getInputStream()); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { response = DOMResponse.load(connection.getInputStream()); } else { logger.error("unknown content-type: " + contentType); } } catch (Exception e) { String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); } } else { logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (Exception e) { logger.error(e); } return response; }
From source file:org.apache.zeppelin.warp10.Warp10Interpreter.java
public Pair<InterpreterResult.Code, String> execRequest(String body) throws Exception { ///*from w w w.j av a 2 s . c o m*/ // Execute the request on current url defined // String url = this.current_Url; url += "/exec"; URL obj = new URL(url); HttpURLConnection con = null; // // If HTTPS execute an HTTPS connection // if (url.startsWith("https")) { con = (HttpsURLConnection) obj.openConnection(); } else { con = (HttpURLConnection) obj.openConnection(); } //add request header con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setChunkedStreamingMode(16384); con.connect(); // // Write the body in the request // OutputStream os = con.getOutputStream(); //GZIPOutputStream out = new GZIPOutputStream(os); PrintWriter pw = new PrintWriter(os); pw.println(body); pw.close(); StringBuffer response = new StringBuffer(); Pair<InterpreterResult.Code, String> resultPair = null; // // If answer equals 200 parse result stream, otherwise error Stream // if (200 == con.getResponseCode()) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } resultPair = new Pair<InterpreterResult.Code, String>(InterpreterResult.Code.SUCCESS, response.toString()); in.close(); con.disconnect(); } else { String fillBackEnd = "Warp10"; if (this.isCzdBackend) { fillBackEnd = "CityzenData"; } String errorLine = "\"Error-Line\":" + con.getHeaderField("X-" + fillBackEnd + "-Error-Line"); String errorMsg = "\"Error-Message\":\"" + con.getHeaderField("X-" + fillBackEnd + "-Error-Message") + "\""; response.append("[{"); response.append(errorLine + ","); response.append(errorMsg); boolean getBody = (null == con.getContentType()); if (!getBody && !con.getContentType().startsWith("text/html")) { getBody = true; } if (getBody) { response.append(",\"Body\":\""); BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); response.append("\""); } response.append("}]"); resultPair = new Pair<InterpreterResult.Code, String>(InterpreterResult.Code.ERROR, response.toString()); con.disconnect(); } // // Return the body message with its associated code (SUCESS or ERROR) // return resultPair; }
From source file:uk.ac.soton.itinnovation.easyjena.core.impl.JenaOntologyManager.java
/** * Checks whether the given URL exists and represents a valid ontology file * * @param location the URL to test//from ww w . ja v a 2 s .c o m * @return whether it exists and is valid or not */ private boolean urlExists(String location) { boolean found = false; try { //Check if the URL is valid, i.e. exists URL url = new URL(location); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("GET"); //don't actually load the file, only connect so the HTTP resonse code can be retrieved huc.connect(); int responseCode = huc.getResponseCode(); String responseMsg = huc.getResponseMessage(); //if the URI exists if (responseCode == 200) { //load file and check whether it's in an allowed format String contentType = huc.getContentType(); //logger.debug("Content type: {}", contentType); String[] allowedContentTypes = { "application/rdf+xml;", "text/turtle", "text/plain", "text/html" }; for (String act : allowedContentTypes) { if (contentType.contains(act)) { found = true; break; } } //TODO: open file and do sanity check and if it fails set found to false again if (!found) { logger.debug("Wrong content type ({}): the document found at URL <{}> " + "is not a valid ontology file", contentType, location); } //HTTP error encountered } else { logger.debug("Could not find ontology at given URL, HTTP error code: {} - {}", responseCode, responseMsg); } } catch (MalformedURLException e) { logger.debug("URL <{}> is invalid", location, e); } catch (IOException e) { logger.debug("Error loading ontology from URL <{}>", location, e); } return found; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** * Verify that Internal OCSP responses are signed by CA signing key. *//* w w w . j a v a 2s. com*/ @Test public void test17OCSPResponseSignature() throws Exception { // Get user and ocspTestCert that we know... loadUserCert(caid); this.helper.reloadKeys(); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceOcsp); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(req.getEncoded()); os.close(); assertTrue("HTTP error", con.getResponseCode() == 200); // Some appserver (Weblogic) responds with // "application/ocsp-response; charset=UTF-8" assertNotNull("No Content-Type in reply.", con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertTrue("Response status not the expected.", response.getStatus() != 200); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); boolean verify = brep .isSignatureValid(new JcaContentVerifierProviderBuilder().build(cacert.getPublicKey())); assertTrue("Signature verification", verify); }
From source file:com.athenahealth.api.APIConnection.java
/** * Make the API call./*from ww w . j a v a 2s . c o m*/ * * This method abstracts away the connection, streams, and readers necessary to make an HTTP * request. It also adds in the Authorization header and token. * * @param verb HTTP method to use * @param path URI to find * @param parameters key-value pairs of request parameters * @param headers key-value pairs of request headers * @param secondcall true if this is the retried request * @return the JSON-decoded response * * @throws AthenahealthException If there is an error making the call. * API-level errors are reported in the return-value. */ private Object call(String verb, String path, Map<String, String> parameters, Map<String, String> headers, boolean secondcall) throws AthenahealthException { try { // Join up a url and open a connection URL url = new URL(path_join(getBaseURL(), version, practiceid, path)); HttpURLConnection conn = openConnection(url); conn.setRequestMethod(verb); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // Set the Authorization header using the token, then do the rest of the headers conn.setRequestProperty("Authorization", "Bearer " + token); if (headers != null) { for (Map.Entry<String, String> pair : headers.entrySet()) { conn.setRequestProperty(pair.getKey(), pair.getValue()); } } // Set the request parameters, if there are any if (parameters != null) { conn.setDoOutput(true); Writer wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); wr.write(urlencode(parameters)); wr.flush(); wr.close(); } // If we get a 401, retry once if (conn.getResponseCode() == 401 && !secondcall) { authenticate(); return call(verb, path, parameters, headers, true); } // The API response is in the input stream on success and the error stream on failure. BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException e) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); String rawResponse = sb.toString(); if (503 == conn.getResponseCode()) throw new AthenahealthException("Service Temporarily Unavailable: " + rawResponse); if (!"application/json".equals(conn.getContentType())) throw new AthenahealthException("Expected application/json response, got " + conn.getContentType() + " instead." + " Content=" + rawResponse); // If it won't parse as an object, it'll parse as an array. Object response; try { response = new JSONObject(rawResponse); } catch (JSONException e) { try { response = new JSONArray(rawResponse); } catch (JSONException e2) { if (Boolean.getBoolean("com.athenahealth.api.dump-response-on-JSON-error")) { System.err.println("Server response code: " + conn.getResponseCode()); Map<String, List<String>> responseHeaders = conn.getHeaderFields(); for (Map.Entry<String, List<String>> header : responseHeaders.entrySet()) for (String value : header.getValue()) { if (null == header.getKey() || "".equals(header.getKey())) System.err.println("Status: " + value); else System.err.println(header.getKey() + "=" + value); } } throw new AthenahealthException( "Cannot parse response from server as JSONObject or JSONArray: " + rawResponse, e2); } } return response; } catch (MalformedURLException mue) { throw new AthenahealthException("Invalid URL", mue); } catch (IOException ioe) { throw new AthenahealthException("I/O error during call", ioe); } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient/*from w w w. j a va 2 s .c o m*/ public void testCreatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception { Package p = createTestPackage("TestCreatePackageFromJAXB"); p.setDescription("desc for testCreatePackageFromJAXB"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("TestCreatePackageFromJAXB", result.getTitle()); assertEquals("desc for testCreatePackageFromJAXB", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/TestCreatePackageFromJAXB/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/TestCreatePackageFromJAXB/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient/*from www .ja va2s . c o m*/ public void testCreatePackageFromDRLAsJaxB(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.setDoOutput(true); //Send request InputStream in = null; OutputStream out = null; try { in = getClass().getResourceAsStream("simple_rules3.drl"); out = connection.getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient// www .jav a2 s.co m public void testCreatePackageFromDRLAsJson(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON); connection.setDoOutput(true); //Send request InputStream in = null; OutputStream out = null; try { in = getClass().getResourceAsStream("simple_rules2.drl"); out = connection.getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_JSON, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }