List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:dlauncher.dialogs.Login.java
private void login_write(String UserName, String Password) { Logger.getGlobal().info("Started login process"); Logger.getGlobal().info("Writing login data.."); try {// w ww . j a v a 2 s . co m url = new URL("http://authserver.mojang.com/authenticate"); final URLConnection con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()))) { writer.write("{\n" + " \"agent\": {" + " \"name\": \"Minecraft\"," + " \"version\": 1" + "\n" + " },\n" + " \"username\": \"" + UserName + "\",\n" + "\n" + " \"password\": \"" + Password + "\",\n" + "}"); writer.close(); } Logger.getGlobal().info("Succesful written login data"); } catch (MalformedURLException ex) { Logger.getGlobal().warning("Failed Writing login data,"); Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex); } catch (IOException ex) { Logger.getGlobal().warning("Failed Writing login data,"); Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex); } }
From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRServerImpl.java
public ResponseType requestCall(RequestType request) { AutoCreate ac = new AutoCreate(); ac.setRequest(request);/*from w w w . j a va 2 s . c om*/ ResponseType response = null; try { Marshaller marshaller = jaxbc.createMarshaller(); Unmarshaller unmarshaller = jaxbc.createUnmarshaller(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); marshaller.marshal(ac, byteStream); String xml = byteStream.toString(); URL url = new URL(this.serverURL); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestProperty("Content-Type", "text/xml"); con.setRequestProperty("Content-transfer-encoding", "text"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); log.info("Sending request: " + xml); out.write(xml); out.flush(); out.close(); InputStream in = con.getInputStream(); int len = 4096; byte[] buffer = new byte[len]; int off = 0; int read = 0; while ((read = in.read(buffer, off, len)) != -1) { off += read; len -= off; } String responseText = new String(buffer, 0, off); log.debug("Received response: " + responseText); Object o = unmarshaller.unmarshal(new ByteArrayInputStream(responseText.getBytes())); if (o instanceof AutoCreate) { AutoCreate acr = (AutoCreate) o; response = acr.getResponse(); } } catch (MalformedURLException e) { log.error("", e); } catch (IOException e) { log.error("", e); } catch (JAXBException e) { log.error("", e); } finally { if (response == null) { response = new ResponseType(); response.setStatus(StatusType.ERROR); response.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR); response.setErrorString("Unknown error occurred sending request to IVR server"); } } return response; }
From source file:org.apache.jcs.auxiliary.lateral.http.broadcast.LateralCacheThread.java
/** Description of the Method */ public void writeObj(URLConnection connection, ICacheElement cb) { try {/*from w w w . ja v a 2s . co m*/ connection.setUseCaches(false); connection.setRequestProperty("CONTENT_TYPE", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream()); log.debug("os = " + os); // Write the ICacheItem to the ObjectOutputStream log.debug("Writing ICacheItem."); os.writeObject(cb); os.flush(); log.debug("closing output stream"); os.close(); } catch (IOException e) { log.error(e); } // end catch }
From source file:org.LexGrid.LexBIG.caCore.test.rest.RESTTest.java
private String callRestfulService(String putString) throws Exception { URL url = new URL(serviceEndPoint + putString); URLConnection urlc = url.openConnection(); urlc.setDoInput(true);/*from w w w. j a va 2s. c o m*/ urlc.setDoOutput(true); PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.close(); //retrieve result BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); return sb.toString(); }
From source file:org.digidoc4j.impl.bdoc.SKTimestampDataLoader.java
@Override public byte[] post(String url, byte[] content) { logger.info("Getting timestamp from " + url); OutputStream out = null;/*from ww w .j a v a2s. c o m*/ InputStream inputStream = null; byte[] result = null; try { URLConnection connection = new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/timestamp-query"); connection.setRequestProperty("Content-Transfer-Encoding", "binary"); connection.setRequestProperty("User-Agent", userAgent); out = connection.getOutputStream(); IOUtils.write(content, out); inputStream = connection.getInputStream(); result = IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(inputStream); } return result; }
From source file:com.linkedin.pinot.perf.PerfBenchmarkDriver.java
public JSONObject postQuery(String query) throws Exception { final JSONObject json = new JSONObject(); json.put("pql", query); final long start = System.currentTimeMillis(); final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection(); conn.setDoOutput(true);//from w w w . j a v a 2 s . c om final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); final String reqStr = json.toString(); writer.write(reqStr, 0, reqStr.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); final String res = sb.toString(); final JSONObject ret = new JSONObject(res); ret.put("totalTime", (stop - start)); if ((ret.getLong("numDocsScanned") > 0) && verbose) { LOGGER.info("reqStr = " + reqStr); LOGGER.info(" Client side time in ms:" + (stop - start)); LOGGER.info("numDocScanned : " + ret.getLong("numDocsScanned")); LOGGER.info("timeUsedMs : " + ret.getLong("timeUsedMs")); LOGGER.info("totalTime : " + ret.getLong("totalTime")); LOGGER.info("res = " + res); } return ret; }
From source file:org.asimba.auth.smsotp.distributor.mollie.MollieOTPDistributor.java
/** * Distribute the OTP to the user<br/> * Requires a configured attribute to be present in the User's Attributes()-collection to * establish the phonenr to send the OneTimePassword to!<br/> * Updates Otp-instance to reflect the result of distributing the password (timessent, timesent) * //from w w w . j a v a 2 s .com * Sources inspired by A-Select SMS AuthSP */ public int distribute(OTP oOtp, IUser oUser) throws OAException, OTPDistributorException { // Are we operational? if (!_bStarted) { throw new OAException(SystemErrors.ERROR_NOT_INITIALIZED); } String sMsg; String sRecipient; IAttributes oUserAttributes; int returncode = 15; // Establish the phonenr to send message to oUserAttributes = oUser.getAttributes(); if (!oUserAttributes.contains(_sPhonenrAttribute)) { _oLogger.error("Unknown phonenr for user " + oUser.getID() + "; missing attribute '" + _sPhonenrAttribute + "'"); throw new OTPDistributorException(returncode); } sRecipient = (String) oUserAttributes.get(_sPhonenrAttribute); // Establish message sMsg = getMessageForPwd(oOtp.getValue()); // Establish URL StringBuffer sbData = new StringBuffer(); try { ArrayList<String> params = new ArrayList<String>(); // Depend on Apache Commons Lang for join params.add(StringUtils.join(new String[] { "gebruikersnaam", URLEncoder.encode(_sUsername, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "wachtwoord", URLEncoder.encode(_sPassword, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "afzender", URLEncoder.encode(_sSenderName, "UTF-8") }, "=")); params.add(StringUtils.join(new String[] { "bericht", URLEncoder.encode(sMsg, "UTF-8") }, "=")); params.add( StringUtils.join(new String[] { "ontvangers", URLEncoder.encode(sRecipient, "UTF-8") }, "=")); String sCGIString = StringUtils.join(params, "&"); returncode++; // 16 URLConnection oURLConnection = _oURL.openConnection(); returncode++; // 17 oURLConnection.setDoOutput(true); OutputStreamWriter oWriter = new OutputStreamWriter(oURLConnection.getOutputStream()); oWriter.write(sCGIString); oWriter.flush(); returncode++; // 18 // Get the response BufferedReader oReader = new BufferedReader(new InputStreamReader(oURLConnection.getInputStream())); String sLine; if ((sLine = oReader.readLine()) != null) { returncode = Integer.parseInt(sLine); } if (returncode != 0) { _oLogger.error("Mollie could not send sms, returncode from Mollie: " + returncode + "."); throw new OTPDistributorException(returncode); } returncode++; // 19 oWriter.close(); oReader.close(); } catch (NumberFormatException e) { _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString() + "\' failed due to number format exception!" + e.getMessage()); throw new OTPDistributorException(returncode); } catch (Exception e) { _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString() + "\' failed (return code=" + returncode + ")! " + e.getMessage()); throw new OTPDistributorException(returncode); } _oLogger.info("Sending to user " + oUser.getID() + " password with value " + oOtp.getValue()); oOtp.registerSent(Long.valueOf(System.currentTimeMillis())); return returncode; }
From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java
/** * Call a Shapeways API with POST/*from w w w. j a v a2 s . co m*/ * * @param apiUrl * @return * @throws Exception */ private String postResponseOld(String apiUrl, Map<String, String> parameters) throws Exception { Log.d(LOG_TAG, "postResponse: url=" + apiUrl); URLConnection urlConnection = getUrlConnection(apiUrl, true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); Request request = new Request(POST); request.addParameter(OAUTH_CONSUMER_KEY, consumerKey); request.addParameter(OAUTH_TOKEN, oauthToken); for (String key : parameters.keySet()) { request.addParameter(key, parameters.get(key)); } request.sign(apiUrl, consumerSecret, oauthTokenSecret); outputStreamWriter.write(request.toString()); outputStreamWriter.close(); return readResponse(urlConnection.getInputStream()); }
From source file:org.intermine.api.mines.HttpRequester.java
@Override public BufferedReader requestURL(final String urlString, final ContentType contentType) { BufferedReader reader = null; OutputStreamWriter writer = null; // TODO: when all friendly mines support mimetype formats then we can remove this. String suffix = "?format=" + contentType.getFormat(); try {/* ww w.jav a2s. c om*/ URL url = new URL(StringUtils.substringBefore(urlString, "?") + suffix); URLConnection conn = url.openConnection(); conn.addRequestProperty("Accept", contentType.getMimeType()); conn.setConnectTimeout(timeout * 1000); // conn accepts millisecond timeout. if (urlString.contains("?")) { // POST String queryString = StringUtils.substringAfter(urlString, "?"); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(queryString); writer.flush(); LOG.info("FriendlyMine URL (POST) " + urlString); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception e) { throw new RuntimeException("Unable to access " + urlString + " exception: " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { LOG.error("Error sending POST request", e); } } } return reader; }
From source file:be.apsu.extremon.probes.tsp.TSPProbe.java
private TimeStampResponse probe(TimeStampRequest request) throws IOException, TSPException { URLConnection connection = this.url.openConnection(); connection.setDoInput(true);/* w w w . j a va 2 s . c o m*/ connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/timestamp-query"); OutputStream outputStream = (connection.getOutputStream()); outputStream.write(request.getEncoded()); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); TimeStampResponse response = new TimeStampResponse(inputStream); inputStream.close(); return response; }