List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java
/** * This methods make a call to ES-Publisher REST API and obtain a valid sessionID * * @return SessionId for the authenticated user *///from ww w. j a va2 s . c om private String login() throws IOException { String sessionID = null; Reader input = null; BufferedWriter writer = null; String authenticationEndpoint = getBaseUrl() + PUBLISHER_APIS_AUTHENTICATE_ENDPOINT; //construct full authenticate endpoint try { //authenticate endpoint URL URL endpointUrl = new URL(authenticationEndpoint); URLConnection urlConn = endpointUrl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); // Specify the content type. urlConn.setRequestProperty(CONTENT_TYPE_HEADER, CONTENT_TYPE); // Send POST output. writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream())); String content = USERNAME + "=" + URLEncoder.encode(USERNAME_VAL, UTF_8) + "&" + PASSWORD + "=" + URLEncoder.encode(PASSWORD_VAl, UTF_8); if (LOG.isDebugEnabled()) { LOG.debug("Send Login Information : " + content); } writer.write(content); writer.flush(); // Get response data. input = new InputStreamReader(urlConn.getInputStream()); JsonElement elem = parser.parse(input); sessionID = elem.getAsJsonObject().getAsJsonObject(AUTH_RESPONSE_WRAP_KEY).get(SESSIONID).toString(); if (LOG.isDebugEnabled()) { LOG.debug("Received SessionID : " + sessionID); } } catch (MalformedURLException e) { LOG.error(getLoginErrorMassage(authenticationEndpoint), e); throw e; } catch (IOException e) { LOG.error(getLoginErrorMassage(authenticationEndpoint), e); throw e; } finally { if (input != null) { try { input.close();// will close the URL connection as well } catch (IOException e) { LOG.error("Failed to close input stream ", e); } } if (writer != null) { try { writer.close();// will close the URL connection as well } catch (IOException e) { LOG.error("Failed to close output stream ", e); } } } return sessionID; }
From source file:net.solarnetwork.node.support.HttpClientSupport.java
/** * HTTP POST data as {@code application/x-www-form-urlencoded} (e.g. a web * form) to a URL./*from w ww. jav a 2s .c o m*/ * * @param url * the URL to post to * @param accept * the value to use for the Accept HTTP header * @param data * the data to encode and send as the body of the HTTP POST * @return the URLConnection after the post data has been sent * @throws IOException * if any IO error occurs * @throws RuntimeException * if the HTTP response code is not within the 200 - 299 range */ protected URLConnection postXWWWFormURLEncodedData(String url, String accept, Map<String, ?> data) throws IOException { URLConnection conn = getURLConnection(url, HTTP_METHOD_POST, accept); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String body = xWWWFormURLEncoded(data); log.trace("Encoded HTTP POST data {} as {}", data, body); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); FileCopyUtils.copy(new StringReader(body), out); if (conn instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) conn; int status = http.getResponseCode(); if (status < 200 || status > 299) { throw new RuntimeException("HTTP result status not in the 200-299 range: " + http.getResponseCode() + " " + http.getResponseMessage()); } } return conn; }
From source file:com.adaptris.core.runtime.AdapterRegistry.java
@Override public void persist(String data, URLString configUrl) throws CoreException, IOException { assertNotNull(configUrl, EXCEPTION_MSG_URL_NULL); URL url = configUrl.getURL(); OutputStream out = null;/* ww w .j a va 2 s .c o m*/ try { if ("file".equalsIgnoreCase(url.getProtocol())) { out = new FileOutputStream(FsHelper.createFileReference(url)); persist(data, out); } else { URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); out = urlConnection.getOutputStream(); persist(data, out); } } finally { IOUtils.closeQuietly(out); } }
From source file:org.dspace.license.CCLookup.java
/** * Passes a set of "answers" to the web service and retrieves a license. * * @param licenseId The identifier of the license class being requested. * @param answers A Map containing the answers to the license fields; * each key is the identifier of a LicenseField, with the value * containing the user-supplied answer. * @param lang The language to request localized elements in. * * @throws IOException/*from ww w . j av a 2 s. c om*/ * * @see CCLicense * @see Map */ public void issue(String licenseId, Map answers, String lang) throws IOException { // Determine the issue URL String issueUrl = this.cc_root + "/license/" + licenseId + "/issue"; // Assemble the "answers" document String answer_doc = "<answers>\n<locale>" + lang + "</locale>\n" + "<license-" + licenseId + ">\n"; Iterator keys = answers.keySet().iterator(); try { String current = (String) keys.next(); while (true) { answer_doc += "<" + current + ">" + (String) answers.get(current) + "</" + current + ">\n"; current = (String) keys.next(); } } catch (NoSuchElementException e) { // exception indicates we've iterated through the // entire collection; just swallow and continue } // answer_doc += "<jurisdiction></jurisidiction>\n"; FAILS with jurisdiction argument answer_doc += "</license-" + licenseId + ">\n</answers>\n"; String post_data; try { post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } URL post_url; try { post_url = new URL(issueUrl); } catch (MalformedURLException e) { return; } URLConnection connection = post_url.openConnection(); // this will not be needed after I'm done TODO: remove connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(post_data); writer.flush(); // end TODO try { // parsing document from input stream java.io.InputStream stream = connection.getInputStream(); this.license_doc = this.parser.build(stream); } catch (JDOMException jde) { log.warn(jde.getMessage()); } catch (Exception e) { log.warn(e.getCause()); } return; }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping("Inboxphp.htm") public ModelAndView Inboxphp(ModelAndView mav, Principal principal) { String name = principal.getName(); List<correoNoLeidos> lta = null; int numTodoscorreosNum = 0; Map<String, String> datosEnv = new HashMap<String, String>(); datosEnv.put("nombre", "pepe"); datosEnv.put("apellido", "Gonzalez"); Gson gson = new Gson(); String jsonOutput = gson.toJson(datosEnv); try {/* w w w . j a v a2s . com*/ //Usamos URLencode para poder enviar la cadena jsonOutput = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(jsonOutput, "UTF-8"); //Establecemos la conexion y enviamos los datos URL url = new URL("http://localhost/php/index.php"); URLConnection con = (URLConnection) url.openConnection(); con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonOutput); wr.flush(); //Recibimos los datos BufferedReader recv = new BufferedReader(new InputStreamReader(con.getInputStream())); //Los mostramos por pantalla String s = recv.readLine(); while (s != null) { System.out.println(s); s = recv.readLine(); } } catch (Exception ex) { } //ModelAndView mav=new ModelAndView(); String r = validaInterfacesRoles.valida(); mav.addObject("menu", r); mav.addObject("numCT", numTodoscorreosNum); mav.addObject("lta", lta); mav.setViewName("Inbox"); return mav; }
From source file:BRHInit.java
public JSONObject json_rpc(String method, JSONArray params) throws Exception { URLConnection conn = rpc_url.openConnection(); if (cookie != null) conn.addRequestProperty("cookie", cookie); JSONObject request = new JSONObject(); request.put("id", false); request.put("method", method); request.put("params", params); conn.setDoOutput(true);/*w w w .ja v a 2 s . com*/ OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); try { wr.write(request.toString()); wr.flush(); } finally { wr.close(); } // Get the response InputStreamReader rd = new InputStreamReader(conn.getInputStream()); try { JSONTokener tokener = new JSONTokener(rd); return (JSONObject) tokener.nextValue(); } finally { rd.close(); } }
From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java
public String getUI(String xmlUI) throws GWTServiceException { String url = null;/*from w w w . ja v a 2 s. c o m*/ if (service.isValidXML(xmlUI)) { logger.fine("XML Send by client : \n" + xmlUI); try { String urlBase = ApplicationCluster.getInstance() .getConfigurationItem(Configuration.FLEX_DEMO_WAR_URL); if (urlBase == null || urlBase.length() == 0) { urlBase = getThreadLocalRequest().getScheme() + "://" + getThreadLocalRequest().getServerName() + ":" + getThreadLocalRequest().getServerPort() + "/qafe-web-flex"; } String urlStore = urlBase + "/store"; logger.fine("URL Store is =" + urlStore); OutputStreamWriter wr = null; BufferedReader rd = null; try { // Send data URL requestURL = new URL(urlStore); URLConnection conn = requestURL.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); String data = "xml" + "=" + xmlUI; wr.write(data); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { url = urlBase + "/index.jsp?uuid=" + line; logger.fine(url); } } finally { wr.close(); rd.close(); } } catch (Exception e) { throw handleException(e); } } else { try { service.getUIFromXML(xmlUI, null, null, getLocale()); } catch (Exception e) { throw handleException(e); } } return url; }
From source file:fr.free.divde.webcam.WebcamApplet.java
public void sendImage(JSObject parameters) { final String url = (String) parameters.getMember("url"); final String format = (String) getJSProperty(parameters, "format", "png"); final Map<String, Object> headers = getJSMapProperty(parameters, "headers"); final JSObject callback = (JSObject) getJSProperty(parameters, "callback", null); imageCapture.captureImage(new ImageListener() { @Override//from www.jav a2s. c o m public void nextFrame(BufferedImage image) { try { URL urlObject = new URL(getDocumentBase(), url); URLConnection connection = urlObject.openConnection(); connection.setDoOutput(true); setHeaders(connection, headers); if (connection.getRequestProperty("content-type") == null) { // default content type connection.setRequestProperty("content-type", "image/" + format); } OutputStream out = connection.getOutputStream(); ImageIO.write(image, format, out); out.flush(); out.close(); if (callback != null) { StringWriter response = new StringWriter(); IOUtils.copy(connection.getInputStream(), response, "UTF-8"); callJS(callback, response.toString()); } } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:TSAClient.java
private byte[] getTSAResponse(byte[] request) throws IOException { LOG.debug("Opening connection to TSA server"); // todo: support proxy servers URLConnection connection = url.openConnection(); connection.setDoOutput(true);//w w w . j av a2 s . c o m connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/timestamp-query"); LOG.debug("Established connection to TSA server"); if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) { connection.setRequestProperty(username, password); } // read response OutputStream output = null; try { output = connection.getOutputStream(); output.write(request); } finally { IOUtils.closeQuietly(output); } LOG.debug("Waiting for response from TSA server"); InputStream input = null; byte[] response; try { input = connection.getInputStream(); response = IOUtils.toByteArray(input); } finally { IOUtils.closeQuietly(input); } LOG.debug("Received response from TSA server"); return response; }
From source file:nl.welteninstituut.tel.la.importers.fitbit.FitbitTask.java
public String postUrl(String url, String data, String authorization) { StringBuilder result = new StringBuilder(); try {//from w w w . ja v a 2 s . c om URLConnection conn = new URL(url).openConnection(); // conn.setConnectTimeout(30); conn.setDoOutput(true); if (authorization != null) conn.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authorization.getBytes()))); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } wr.close(); rd.close(); } catch (Exception e) { } return result.toString(); }