List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.util.httpAccount.java
public String setAccountObject(AccountLight account, String user) throws UnsupportedEncodingException, MalformedURLException, IOException { String respuesta = null;/* www . ja va 2 s. c o m*/ String myUrl = "http://192.168.5.44/app_dev.php/cus/setaccount/" + user + ".json"; URL url = new URL(myUrl); try { //abrimos la conexin URLConnection conn = url.openConnection(); //especificamos que vamos a escribir conn.setDoOutput(true); String data = URLEncoder.encode("firstName", "UTF-8") + "=" + URLEncoder.encode(account.getFirstName(), "UTF-8"); data += "&" + URLEncoder.encode("lastName", "UTF-8") + "=" + URLEncoder.encode(account.getLastName(), "UTF-8"); data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(account.getAddress(), "UTF-8"); data += "&" + URLEncoder.encode("city", "UTF-8") + "=" + URLEncoder.encode(account.getCity(), "UTF-8"); data += "&" + URLEncoder.encode("postalCode", "UTF-8") + "=" + URLEncoder.encode(account.getPostalCode(), "UTF-8"); data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(account.getEmail(), "UTF-8"); data += "&" + URLEncoder.encode("languaje", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.getLanguaje_id()), "UTF-8"); data += "&" + URLEncoder.encode("notifyEmail", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.isNotifyEmail()), "UTF-8"); data += "&" + URLEncoder.encode("notifyFlag", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.isNotityFlag()), "UTF-8"); //escribimos try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } //obtenemos el flujo de lectura BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String linea; //procesamos al salida while ((linea = rd.readLine()) != null) { respuesta += linea; } } catch (Exception e) { e.printStackTrace(); respuesta = null; } System.out.println(respuesta); // TODO code application logic here return respuesta; }
From source file:org.apache.jsp.fileUploader_jsp.java
private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId, Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request, HttpServletResponse response) {//from w w w .j a v a 2 s . co m String charset = "UTF-8"; String url = ""; try { if (isJson) { //first check if bytes are actually json try { new JsonParser().parse(new String(bytes)); } catch (Exception ex) { return "Failed, file was not valid JSON"; } if (newShare) url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } else { if (newShare) url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/binary/" + prevId + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } if (localCookie) CookieHandler.setDefault(cm); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); } if (mimeType != null && mimeType.length() > 0) connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset); DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(bytes); DataInputStream responseStream = new DataInputStream(connection.getInputStream()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = responseStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } String json = buffer.toString(); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } buffer.flush(); buffer.close(); output.close(); responseStream.close(); if (isJson) { jsonResponse jr = new Gson().fromJson(json, jsonResponse.class); if (jr == null) { return "Failed: " + json; } if (jr.response.success == true) { if (jr.data != null && jr.data._id != null) { addRemoveCommunities(jr.data._id, communities, request, response); return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload } } return "Upload Failed: " + jr.response.message; } else { modResponse mr = new Gson().fromJson(json, modResponse.class); if (mr == null) { return "Failed: " + json; } if (mr.response.success == true) { if (prevId != null && mr.data == null) { addRemoveCommunities(prevId, communities, request, response); return prevId; } else { addRemoveCommunities(mr.data, communities, request, response); return mr.data; //When a new upload, mr.data contains the ShareID for the upload } } else { return "Upload Failed: " + mr.response.message; } } } catch (IOException e) { e.printStackTrace(); return "Upload Failed: " + e.getMessage(); } }
From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java
/** * Requests that a electronically signed CDA Document object be stored * /*from www . j a v a 2 s . c o m*/ * @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.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 ww w .j a v a 2 s . c om*/ 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:com.adobe.aem.demo.communities.Loader.java
private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath, String resourceType) {/* w w w. ja v a 2s . 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.sources_jsp.java
private String postToRestfulApi(String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try {/*from w w w . jav a 2s . c o 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:com.techventus.server.voice.Voice.java
/** * Send an SMS.//from w ww. j a v a 2s .c om * * @param destinationNumber the destination number * @param txt the Text of the message. Messages longer than the allowed * character length will be split into multiple messages. * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String sendSMS(String destinationNumber, String txt) throws IOException { String out = ""; String smsdata = ""; smsdata += URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc); smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc); smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/"); URLConnection smsconn = smsurl.openConnection(); smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); smsconn.setRequestProperty("User-agent", USER_AGENT); smsconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream()); callwr.write(smsdata); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.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
/** * Send an SMS./*from w w w. j a va 2 s.c o m*/ * * @param destinationNumber the destination number * @param txt the Text of the message. Messages longer than the allowed * character length will be split into multiple messages. * @param id the Text of the message. Messages longer than the allowed * character length will be split into multiple messages. * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String sendSMS(String destinationNumber, String txt, String id) throws IOException { String out = ""; String smsdata = ""; smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc); smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc); smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); System.out.println("smsdata: " + smsdata); URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/"); URLConnection smsconn = smsurl.openConnection(); smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); smsconn.setRequestProperty("User-agent", USER_AGENT); smsconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream()); callwr.write(smsdata); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.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
/** * Cancel a call that was just placed.// w w w .j ava 2s .co m * * @param originNumber * the origin number * @param destinationNumber * the destination number * @param phoneType * the phone type * @return the string * @throws IOException * Signals that an I/O exception has occurred. */ public String cancelCall(String originNumber, String destinationNumber, String phoneType) throws IOException { String out = ""; String calldata = ""; calldata += URLEncoder.encode("outgoingNumber", enc) + "=" + URLEncoder.encode("undefined", enc); calldata += "&" + URLEncoder.encode("forwardingNumber", enc) + "=" + URLEncoder.encode("undefined", enc); calldata += "&" + URLEncoder.encode("cancelType", enc) + "=" + URLEncoder.encode("C2C", enc); calldata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); // POST /voice/call/connect/ outgoingNumber=[number to // call]&forwardingNumber=[forwarding // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from // page] URL callURL = new URL("https://www.google.com/voice/b/0/call/cancel/"); 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); 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
/** * Mark a Conversation with a known Message ID as read. * * @param msgID the msg id/*from w w w .j a v a2 s . c o m*/ * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String markAsRead(String msgID) throws IOException { String out = ""; StringBuffer calldata = new StringBuffer(); // POST /voice/inbox/mark/ // messages=[messageID] // &read=1 // &_rnr_se=[pull from page] calldata.append("messages="); calldata.append(URLEncoder.encode(msgID, enc)); calldata.append("&read=1"); calldata.append("&_rnr_se="); calldata.append(URLEncoder.encode(rnrSEE, enc)); URL callURL = new URL(markAsReadString); 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; }