List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java
/** * Requests that a electronically signed CDA Document object be stored * /*from w ww. j a va2 s. com*/ * @param storeUrl */ private void requestStoreSignedConsent(String storeUrl) { try { URL url = new URL(strRelURL + storeUrl); URLConnection conn = url.openConnection(); conn.setRequestProperty("cookie", strCookie); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Character-Encoding", "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); DOMSource domSource = new DOMSource(cda); StringWriter owriter = new StringWriter(); StreamResult result = new StreamResult(owriter); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); ByteArrayOutputStream bStream = new ByteArrayOutputStream(); ObjectOutputStream oStream = new ObjectOutputStream(bStream); oStream.writeObject(cda); byte[] byteVal = bStream.toByteArray(); OutputStream ops = conn.getOutputStream(); ops.write(byteVal); InputStream is = conn.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(new InputStreamReader(is, "UTF8"), writer); String s = writer.toString(); is.close(); JSONObject jso = new JSONObject(s); boolean success = jso.getBoolean("success"); String message = jso.getString("message"); if (success) { JOptionPane.showMessageDialog(this, message, "Erfolg", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, message, "Fehler", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.orbeon.oxf.util.Connection.java
/** * Open the connection. This sends request headers, request body, and reads status and response headers. * * @return connection result *///from ww w .j a va 2 s . c om public ConnectionResult connect() { final boolean isDebugEnabled = indentedLogger.isDebugEnabled(); // Perform connection final String scheme = connectionURL.getProtocol(); if (isHTTPOrHTTPS(scheme) || (httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf")))) { // http MUST be supported // https SHOULD be supported // file SHOULD be supported try { // Create URL connection object final URLConnection urlConnection = connectionURL.openConnection(); final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection) ? (HTTPURLConnection) urlConnection : null; // Whether a message body must be sent final boolean hasRequestBody = httpMethod.equals("POST") || httpMethod.equals("PUT"); urlConnection.setDoInput(true); urlConnection.setDoOutput(hasRequestBody); // Configure HTTPURLConnection if (httpURLConnection != null) { // Set state if possible httpURLConnection.setCookieStore(this.cookieStore); // Set method httpURLConnection.setRequestMethod(httpMethod); // Set credentials if (credentials != null) { httpURLConnection.setUsername(credentials.username); if (credentials.password != null) httpURLConnection.setPassword(credentials.password); if (credentials.preemptiveAuthentication != null) httpURLConnection.setPreemptiveAuthentication(credentials.preemptiveAuthentication); if (credentials.domain != null) httpURLConnection.setDomain(credentials.domain); } } // Update request headers { // Handle SOAP // Set request Content-Type, SOAPAction or Accept header if needed final boolean didSOAP = handleSOAP(indentedLogger, httpMethod, headersMap, contentType, hasRequestBody); // Set request content type if (!didSOAP && hasRequestBody) { final String actualContentType = (contentType != null) ? contentType : "application/xml"; headersMap.put("Content-Type", new String[] { actualContentType }); indentedLogger.logDebug(LOG_TYPE, "setting header", "Content-Type", actualContentType); } } // Set headers on connection final List<String> headersToLog; if (headersMap != null && headersMap.size() > 0) { headersToLog = isDebugEnabled ? new ArrayList<String>() : null; for (Map.Entry<String, String[]> currentEntry : headersMap.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); if (currentHeaderValues != null) { // Add all header values as "request properties" for (String currentHeaderValue : currentHeaderValues) { urlConnection.addRequestProperty(currentHeaderName, currentHeaderValue); if (headersToLog != null) { headersToLog.add(currentHeaderName); headersToLog.add(currentHeaderValue); } } } } } else { headersToLog = null; } // Log request details except body if (isDebugEnabled) { // Basic connection information final URI connectionURI; try { String userInfo = connectionURL.getUserInfo(); if (userInfo != null) { final int colonIndex = userInfo.indexOf(':'); if (colonIndex != -1) userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx";// hide password in logs } connectionURI = new URI(connectionURL.getProtocol(), userInfo, connectionURL.getHost(), connectionURL.getPort(), connectionURL.getPath(), connectionURL.getQuery(), connectionURL.getRef()); } catch (URISyntaxException e) { throw new OXFException(e); } indentedLogger.logDebug(LOG_TYPE, "opening URL connection", "method", httpMethod, "URL", connectionURI.toString(), "request Content-Type", contentType); // Log all headers if (headersToLog != null) { final String[] strings = new String[headersToLog.size()]; indentedLogger.logDebug(LOG_TYPE, "request headers", headersToLog.toArray(strings)); } } // Write request body if needed if (hasRequestBody) { // Case of empty body if (messageBody == null) messageBody = new byte[0]; // Log message body for debugging purposes if (logBody) logRequestBody(indentedLogger, contentType, messageBody); // Set request body on connection httpURLConnection.setRequestBody(messageBody); } // Connect urlConnection.connect(); if (httpURLConnection != null) { // Get state if possible // This is either the state we set above before calling connect(), or a new state if we didn't provide any this.cookieStore = httpURLConnection.getCookieStore(); } // Create result final ConnectionResult connectionResult = new ConnectionResult(connectionURL.toExternalForm()) { @Override public void close() { if (getResponseInputStream() != null) { try { getResponseInputStream().close(); } catch (IOException e) { throw new OXFException( "Exception while closing input stream for action: " + connectionURL); } } if (httpURLConnection != null) httpURLConnection.disconnect(); } }; // Get response information that needs to be forwarded { // Status code connectionResult.statusCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode() : 200; // Headers connectionResult.responseHeaders = urlConnection.getHeaderFields(); connectionResult.setLastModified(NetUtils.getLastModifiedAsLong(urlConnection)); // Content-Type connectionResult.setResponseContentType(urlConnection.getContentType(), "application/xml"); } // Log response details except body if (isDebugEnabled) { connectionResult.logResponseDetailsIfNeeded(indentedLogger, Level.DEBUG, LOG_TYPE); } // Response stream connectionResult.setResponseInputStream(urlConnection.getInputStream()); // Log response body if (isDebugEnabled) { connectionResult.logResponseBody(indentedLogger, Level.DEBUG, LOG_TYPE, logBody); } return connectionResult; } catch (IOException e) { throw new ValidationException(e, new LocationData(connectionURL.toExternalForm(), -1, -1)); } } else if (!httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf"))) { // TODO: implement writing to file: and oxf: // SHOULD be supported (should probably support oxf: as well) throw new OXFException("submission URL scheme not yet implemented: " + scheme); } else if (scheme.equals("mailto")) { // TODO: implement sending mail // MAY be supported throw new OXFException("submission URL scheme not yet implemented: " + scheme); } else { throw new OXFException("submission URL scheme not supported: " + scheme); } }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting private void tsaRequest() throws Exception { final Random rand = new Random(); final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); boolean doRun = true; do {/* w w w.j a v a 2 s .c o m*/ final int nonce = rand.nextInt(); byte[] digest = new byte[20]; if (instring != null) { final byte[] digestBytes = instring.getBytes("UTF-8"); final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC"); dig.update(digestBytes); digest = dig.digest(); // When we have given input, we don't want to loop doRun = false; } if (infilestring != null) { // TSPAlgorithms constants changed from Strings to ASN1Encoded objects digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId()); doRun = false; } final byte[] hexDigest = Hex.encode(digest); if (LOG.isDebugEnabled()) { LOG.debug("MessageDigest=" + new String(hexDigest)); } final TimeStampRequest timeStampRequest; if (inreqstring == null) { LOG.debug("Generating a new request"); timeStampRequestGenerator.setCertReq(certReq); if (reqPolicy != null) { timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); } else { LOG.debug("Reading request from file"); timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring)); } final byte[] requestBytes = timeStampRequest.getEncoded(); if (outreqstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(requestBytes); } else { outBytes = requestBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outreqstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } keyStoreOptions.setupHTTPS(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(urlstring); // Take start time final long startMillis = System.currentTimeMillis(); final long startTime = System.nanoTime(); if (LOG.isDebugEnabled()) { LOG.debug("Sending request at: " + startMillis); } urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(requestBytes); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) { baos.write(b); } // Take stop time final long estimatedTime = System.nanoTime() - startTime; LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms"); final byte[] replyBytes = baos.toByteArray(); if (outrepstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(replyBytes); } else { outBytes = replyBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outrepstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.info("TimeStampRequest validated"); if (LOG.isDebugEnabled()) { final Date genTime; if (timeStampResponse.getTimeStampToken() != null && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) { genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); } else { genTime = null; } LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo() + "): " + timeStampResponse.getStatusString() + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n"); } if (doRun) { Thread.sleep(sleep); } } while (doRun); }
From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java
private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception { // Get the url... String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL); // add GET parameters to the urlString... Iterator<String> i = parametersMap.keySet().iterator(); String div = "?"; URL url = new URL(urlString); if (url.getQuery() != null) div = "&"; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_GET_PARAM_")) { String paramName = keyName.substring("XML_GET_PARAM_".length()); String value = (String) getParameterValue(keyName); urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; }/* w w w .jav a2s .c om*/ } url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("file")) { // do nothing return JRXmlUtils.parse(url.openStream()); } else if (url.getProtocol().toLowerCase().equals("http") || url.getProtocol().toLowerCase().equals("https")) { String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME); String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD); if (url.getProtocol().toLowerCase().equals("https")) { JRPropertiesUtil dPROP = PropertiesHelper.DPROP; String socketFactory = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory"); if (socketFactory == null) { socketFactory = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory"); } if (socketFactory != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultSSLSocketFactory( (SSLSocketFactory) Class.forName(socketFactory).newInstance()); } else { log.debug("No SSLSocketFactory defined, using default"); } String hostnameVerifyer = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier"); if (hostnameVerifyer == null) { hostnameVerifyer = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier"); } if (hostnameVerifyer != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultHostnameVerifier( (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance()); } else { log.debug("No HostnameVerifier defined, using default"); } } URLConnection conn = url.openConnection(); if (username != null && username.length() > 0 && password != null) { ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes()); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); Base64Encoder enc = new Base64Encoder(bytesIn, dataOut); enc.process(); String encoding = dataOut.toString(); conn.setRequestProperty("Authorization", "Basic " + encoding); } // add POST parameters to the urlString... i = parametersMap.keySet().iterator(); String data = ""; div = ""; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_POST_PARAM_")) { String paramName = keyName.substring("XML_POST_PARAM_".length()); String value = (String) getParameterValue(keyName); data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; } } conn.setDoOutput(true); if (data.length() > 0) { conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); } try { return XMLUtils.parseNoValidation(conn.getInputStream()); } catch (SAXException e) { throw new JRException("Failed to parse the xml document", e); } catch (IOException e) { throw new JRException("Failed to parse the xml document", e); } catch (ParserConfigurationException e) { throw new JRException("Failed to create a document builder factory", e); } // return JRXmlUtils.parse(conn.getInputStream()); } else { throw new JRException("URL protocol not supported"); } }
From source file:org.apache.jsp.communities_jsp.java
public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {// www . j a va 2 s . co m ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } }
From source file:com.adobe.aem.demo.communities.Loader.java
private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath, String resourceType) {// w w w . j a v a 2 s.c o m if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) { URLConnection urlConn = null; DataOutputStream printout = null; BufferedReader input = null; String tmp = null; try { URL pageurl = new URL(pageURL); StringBuffer sb = new StringBuffer( "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>"); sb.append("<events>" + event + "</events>"); sb.append("<pageURL>" + pageURL + "</pageURL>"); sb.append("<pageName>" + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":") + "</pageName>"); sb.append("<evar1>" + resourcePath + "</evar1>"); sb.append("<evar2>" + resourceType + "</evar2>"); sb.append("<visitorID>demomachine</visitorID>"); sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>"); sb.append("</request>"); logger.debug("New Analytics Event: " + sb.toString()); URL sitecaturl = new URL("http://" + analytics); urlConn = sitecaturl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); printout.writeBytes(sb.toString()); printout.flush(); printout.close(); input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while (null != ((tmp = input.readLine()))) { logger.debug(tmp); } printout.close(); input.close(); } catch (Exception ex) { logger.error(ex.getMessage()); } } }
From source file:org.apache.jsp.communities_jsp.java
private String postToRestfulApi(String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try {//from w ww.ja v a 2s . co m URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { //System.out.println("Exception: " + e.getMessage()); } return result; }
From source file:org.apache.jsp.sources_jsp.java
public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {//from ww w.j a va 2 s.co m ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } }
From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java
private String sendPostRequest(String urlAddress, String data, int redirects) throws MalformedURLException, IOException { String result = ""; if (urlAddress.startsWith("https:")) { TrustManagerManipulator.allowAllSSL(); }/* w ww. j ava2s . c o m*/ URLConnection urlConnection = new URL(urlAddress).openConnection(); if (cookie != null) urlConnection.setRequestProperty("Cookie", cookie); if (apiKey != null) urlConnection.setRequestProperty("Cookie", apiKey); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); ((HttpURLConnection) urlConnection).setRequestMethod("POST"); // Post JSON string to URL OutputStream os = urlConnection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); int status = ((HttpURLConnection) urlConnection).getResponseCode(); // normally, 3xx is redirect if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { if (redirects <= 5) { String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location"); if (null != newUrlAddress) { return sendPostRequest(newUrlAddress, data, redirects + 1); } } //(else carry on, will exception out or something below) } } //TESTED // Receive results back from API InputStream inStream = urlConnection.getInputStream(); result = IOUtils.toString(inStream, "UTF-8"); inStream.close(); //save cookie if cookie is null if (cookie == null) { String headername; for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) { if (headername.equals("Set-Cookie")) { cookie = urlConnection.getHeaderField(i); break; } } } return result; }