List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.techventus.server.voice.Voice.java
/** * Mark a Conversation with a known Message ID as unread. * * @param msgID the msg id// ww w . j av a 2 s .c o m * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String markUnRead(String msgID) throws IOException { String out = ""; StringBuffer calldata = new StringBuffer(); // POST /voice/inbox/mark/ // messages=[messageID] // &read=0 // &_rnr_se=[pull from page] calldata.append("messages="); calldata.append(URLEncoder.encode(msgID, enc)); calldata.append("&read=0"); calldata.append("&_rnr_se="); calldata.append(URLEncoder.encode(rnrSEE, enc)); URL callURL = new URL("https://www.google.com/voice/b/0/inbox/mark"); URLConnection callconn = callURL.openConnection(); callconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); callconn.setRequestProperty("User-agent", USER_AGENT); callconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(callconn.getOutputStream()); callwr.write(calldata.toString()); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(callconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
From source file:com.techventus.server.voice.Voice.java
/** * Delete message./*from www . j a v a2 s. co m*/ * * @param msgID the msg id * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String deleteMessage(String msgID) throws IOException { String out = ""; StringBuffer calldata = new StringBuffer(); // POST /voice/inbox/deleteMessages/ // messages=[messageID] // &trash=1 // &_rnr_se=[pull from page] calldata.append("messages="); calldata.append(URLEncoder.encode(msgID, enc)); calldata.append("&trash=1"); calldata.append("&_rnr_se="); calldata.append(URLEncoder.encode(rnrSEE, enc)); URL callURL = new URL("https://www.google.com/voice/b/0/inbox/deleteMessages/"); URLConnection callconn = callURL.openConnection(); callconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); callconn.setRequestProperty("User-agent", USER_AGENT); callconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(callconn.getOutputStream()); callwr.write(calldata.toString()); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(callconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
From source file:com.techventus.server.voice.Voice.java
/** * Place a call./*from ww w . j av a2 s. c om*/ * * @param originNumber * the origin number * @param destinationNumber * the destination number * @param phoneType * the phone type, this is a number such as 1,2,7 formatted as a String * @return the raw response string received from Google Voice. * @throws IOException * Signals that an I/O exception has occurred. */ public String call(String originNumber, String destinationNumber, String phoneType) throws IOException { String out = ""; StringBuffer calldata = new StringBuffer(); // POST /voice/call/connect/ // outgoingNumber=[number to call] // &forwardingNumber=[forwarding number] // &subscriberNumber=undefined // &phoneType=[phone type from google] // &remember=0 // &_rnr_se=[pull from page] calldata.append("outgoingNumber="); calldata.append(URLEncoder.encode(destinationNumber, enc)); calldata.append("&forwardingNumber="); calldata.append(URLEncoder.encode(originNumber, enc)); calldata.append("&subscriberNumber=undefined"); calldata.append("&phoneType="); calldata.append(URLEncoder.encode(phoneType, enc)); calldata.append("&remember=0"); calldata.append("&_rnr_se="); calldata.append(URLEncoder.encode(rnrSEE, enc)); URL callURL = new URL("https://www.google.com/voice/b/0/call/connect/"); URLConnection callconn = callURL.openConnection(); callconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); callconn.setRequestProperty("User-agent", USER_AGENT); callconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(callconn.getOutputStream()); callwr.write(calldata.toString()); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(callconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
From source file:com.techventus.server.voice.Voice.java
/** * Executes the enable/disable action with the provided url params. * * @param paraString the URL Parameters (encoded), ie ?auth=3248sdf7234&enable=0&phoneId=1&enable=1&phoneId=2&_rnr_se=734682ghdsf * @return the raw response of the disable action. * @throws IOException Signals that an I/O exception has occurred. */// w ww . j av a2 s . co m private String phonesEnableDisableApply(String paraString) throws IOException { String out = ""; // POST /voice/call/connect/ outgoingNumber=[number to // call]&forwardingNumber=[forwarding // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from // page] // if (PRINT_TO_CONSOLE) System.out.println(phoneEnableURLString); if (PRINT_TO_CONSOLE) System.out.println(paraString); URL requestURL = new URL(phoneEnableURLString); URLConnection conn = requestURL.openConnection(); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); conn.setRequestProperty("User-agent", USER_AGENT); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream()); callwr.write(paraString); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
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(); }/*from w ww. j a v a 2s . 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; }
From source file:com.techventus.server.voice.Voice.java
/** * Enables/disables the call Announcement setting (general for all phones). * * @param announceCaller <br/>//from w ww .j ava 2 s. co m * true Announces caller's name and gives answering options <br/> * false Directly connects calls when phones are answered * @return the raw response of the disable action. * @throws IOException Signals that an I/O exception has occurred. */ public String setCallPresentation(boolean announceCaller) throws IOException { String out = ""; URL requestURL = new URL(generalSettingsURLString); /** 0 for enable, 1 for disable **/ String announceCallerStr = ""; if (announceCaller) { announceCallerStr = "0"; if (PRINT_TO_CONSOLE) System.out.println("Turning caller announcement on."); } else { announceCallerStr = "1"; if (PRINT_TO_CONSOLE) System.out.println("Turning caller announcement off."); } String paraString = ""; paraString += URLEncoder.encode("directConnect", enc) + "=" + URLEncoder.encode(announceCallerStr, enc); paraString += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); URLConnection conn = requestURL.openConnection(); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); conn.setRequestProperty("User-agent", USER_AGENT); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream()); callwr.write(paraString); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java
private ValidateResponse runHTTP(final X509Certificate cert) throws Exception { final URL processServlet = new URL(useSSL ? "https" : "http", hosts[0], port, servlet); OutputStream out = null;//from w ww.j a v a 2 s . co m InputStream in = null; try { final URLConnection conn = processServlet.openConnection(); conn.setDoOutput(true); conn.setAllowUserInteraction(false); final StringBuilder sb = new StringBuilder(); sb.append("--" + BOUNDARY); sb.append(CRLF); try { final int workerId = Integer.parseInt(service); sb.append("Content-Disposition: form-data; name=\"workerId\""); sb.append(CRLF); sb.append(CRLF); sb.append(workerId); } catch (NumberFormatException e) { sb.append("Content-Disposition: form-data; name=\"workerName\""); sb.append(CRLF); sb.append(CRLF); sb.append(service); } sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"processType\""); sb.append(CRLF); sb.append(CRLF); sb.append("validateCertificate"); sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"datafile\""); sb.append("; filename=\""); sb.append(certPath.getAbsolutePath()); sb.append("\""); sb.append(CRLF); sb.append("Content-Type: application/octet-stream"); sb.append(CRLF); sb.append("Content-Transfer-Encoding: binary"); sb.append(CRLF); sb.append(CRLF); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = conn.getOutputStream(); out.write(sb.toString().getBytes()); out.write(cert.getEncoded()); out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); out.flush(); // Get the response in = conn.getInputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); int len; final byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); // read string from response final String response = os.toString(); final String[] responseParts = response.split(";"); // last part of the response string can by empty (revocation date) if (responseParts.length < 4 || responseParts.length > 5) { throw new IOException("Malformed HTTP response"); } final String revocationDateString = responseParts.length == 4 ? null : responseParts[4]; final Date revocationDate = revocationDateString != null && revocationDateString.length() > 0 ? new Date(Integer.valueOf(revocationDateString)) : null; final Validation validation = new Validation(cert, null, Validation.Status.valueOf(responseParts[0]), responseParts[2], revocationDate, Integer.valueOf(responseParts[3])); final ValidateResponse validateResponse = new ValidateResponse(validation, responseParts[1].split(",")); return validateResponse; } catch (IOException e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (in != null) { try { in.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }
From source file:com.adobe.aem.demomachine.communities.Loader.java
private static void postAnalytics(String analytics, String body) { if (analytics != null && body != null) { URLConnection urlConn = null; DataOutputStream printout = null; BufferedReader input = null; String tmp = null;/*from w w w. java2 s . c o m*/ try { logger.debug("New Analytics Event: " + body); 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(body); 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.warn("Connectivity error: " + ex.getMessage()); } finally { try { input.close(); printout.close(); } catch (Exception e) { // Omitted } } } }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/*w ww . j ava2 s . co m*/ URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * /*www . j a va 2 s . c om*/ * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String) */ public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig, RegressionTestType regressionConfig, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeWs"; String actionName = "REGRESSION_TEST"; // Check the input parameter values: if (cisServerConfig == null || regressionConfig == null) { throw new CompositeException( "XML Configuration objects are not initialized when trying to run Regression test."); } URLConnection urlConn = null; BufferedReader rd = null; OutputStreamWriter wr = null; int rows = 0; String host = cisServerConfig.getHostname(); int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port boolean useHttps = cisServerConfig.isUseHttps(); // Execute the webservice try { // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { boolean encrypt = item.encrypt; // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting. if (useHttps && !encrypt) { encrypt = true; RegressionManagerUtils.printOutputStr(printOutputType, "summary", "The regression input file encrypt=false has been overridden by useHttps=true for path=" + item.path, ""); } String urlString = "http://" + host + ":" + wsPort + item.path; if (encrypt) { urlString = "https://" + host + ":" + (wsPort + 2) + item.path; } RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, ""); URL url = new URL(urlString); urlConn = url.openConnection(); if (encrypt) { // disable hostname verification ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }); } // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users String credentials = cisServerConfig.getUser() + ":" + CommonUtils.decrypt(cisServerConfig.getPassword()); String encoded = Base64EncodeDecode.encodeString(credentials); urlConn.setRequestProperty("Authorization", "Basic " + encoded); urlConn.setRequestProperty("SOAPAction", item.action); urlConn.setRequestProperty("Content-Type", item.contentType); urlConn.setDoOutput(true); wr = new OutputStreamWriter(urlConn.getOutputStream()); wr.write(item.input); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = rd.readLine()) != null) { rows++; buf.append(line); if (outputFile != null) CommonUtils.appendContentToFile(outputFile, line); } line = buf.toString(); RegressionManagerUtils.printOutputStr(printOutputType, "results", line, ""); if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("Fault encountered."); } if (line.trim().length() == 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("No response document."); } urlConn.getInputStream().close(); // urlConn.getOutputStream().flush(); wr.close(); rd.close(); RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } return rows; } catch (IOException e) { try { HttpURLConnection httpConn = (HttpURLConnection) urlConn; BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = brd.readLine()) != null) { buf.append(line + "\n"); } brd.close(); String error = buf.toString(); throw new ApplicationException("executeWs(): " + error, e); } catch (Exception err) { String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]"; //debug: System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************"); throw new ApplicationException("executeWs(): " + error, err); } } finally { try { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } } catch (Exception e) { rd = null; wr = null; throw new CompositeException( "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): " + e.getMessage()); } } }