List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Update hero in database//from ww w. jav a 2 s . c om * @param id hero id * @param name hero name * @param race hero race * @param xp hero experience */ private static void updateHero(String id, String name, String race, String xp) { try { HeroDTO h = new HeroDTO(); h.setId(Long.parseLong(id)); h.setName(name); h.setRace(race); h.setXp(Integer.parseInt(xp)); JSONObject jsonObject = new JSONObject(h); URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/put"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("Updated hero with id: " + h.getId()); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when updating hero"); System.out.println(e); } }
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Create new role in database/*from w ww .j a v a2 s. c o m*/ * @param name role id * @param description role desc * @param energy role energy * @param attack role attack * @param defense role defense */ private static void createRole(String name, String description, String energy, String attack, String defense) { try { RoleDTO r = new RoleDTO(); r.setName(name); r.setDescription(description); r.setEnergy(Integer.parseInt(energy)); r.setAttack(Integer.parseInt(attack)); r.setDefense(Integer.parseInt(defense)); JSONObject jsonObject = new JSONObject(r); URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/post"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("New role " + r.getName() + " was created."); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when creating new role"); System.out.println(e); } }
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Update role in database/*from www . j a v a 2s . c o m*/ * @param id role id * @param name role name * @param description role desc * @param energy role energy * @param attack role attack * @param defense role defense */ private static void updateRole(String id, String name, String description, String energy, String attack, String defense) { try { RoleDTO r = new RoleDTO(); r.setId(Long.parseLong(id)); r.setName(name); r.setDescription(description); r.setEnergy(Integer.parseInt(energy)); r.setAttack(Integer.parseInt(attack)); r.setDefense(Integer.parseInt(defense)); JSONObject jsonObject = new JSONObject(r); URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/put"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("Updated role with id: " + r.getId()); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when updating role"); System.out.println(e); } }
From source file:sturesy.util.web.WebCommands2.java
/** * Sends a post to the specified url/*from ww w. j ava 2s .c o m*/ * * @param url * URL * @param data * Base64 encoded JSONObject * @param hashed * Hash of data used for verification * @return response * @throws IOException */ public static String sendPost(URL url, String data, String hashed) throws IOException { URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod("POST"); } else if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setRequestMethod("POST"); } OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write("data=" + data + "&hash=" + hashed); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = rd.readLine()) != null) { buffer.append(line); } wr.close(); rd.close(); return buffer.toString(); }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static int sendRequestToRetriveHeaders(String addUrl, String query, String contentType) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);//from w ww .j a va 2 s . com connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", contentType + ";charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } HttpURLConnection httpConn = (HttpURLConnection) connection; int responseCode = httpConn.getResponseCode(); return responseCode; }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static int sendRequestToRetriveHeaders(String addUrl, String query) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);// w w w .jav a2s . c o m connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } HttpURLConnection httpConn = (HttpURLConnection) connection; int responseCode = httpConn.getResponseCode(); return responseCode; }
From source file:info.magnolia.cms.exchange.simple.Transporter.java
/** * http form multipart form post/*w w w .ja v a 2s . c o m*/ * @param connection * @param activationContent * @throws ExchangeException */ public static void transport(URLConnection connection, ActivationContent activationContent) throws ExchangeException { FileInputStream fis = null; DataOutputStream outStream = null; try { byte[] buffer = new byte[BUFFER_SIZE]; connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY); connection.setRequestProperty("Cache-Control", "no-cache"); outStream = new DataOutputStream(connection.getOutputStream()); outStream.writeBytes("--" + BOUNDARY + "\r\n"); // set all resources from activationContent Iterator fileNameIterator = activationContent.getFiles().keySet().iterator(); while (fileNameIterator.hasNext()) { String fileName = (String) fileNameIterator.next(); fis = new FileInputStream(activationContent.getFile(fileName)); outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileName + "\"\r\n"); outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n"); while (true) { synchronized (buffer) { int amountRead = fis.read(buffer); if (amountRead == -1) { break; } outStream.write(buffer, 0, amountRead); } } fis.close(); outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n"); } outStream.flush(); outStream.close(); log.debug("Activation content sent as multipart/form-data"); } catch (Exception e) { throw new ExchangeException( "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.error("Exception caught", e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { log.error("Exception caught", e); } } } }
From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java
public static OMElement sendXMLRequest(String addUrl, String query) throws MalformedURLException, IOException, XMLStreamException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);/*from w w w . j a v a 2 s . com*/ connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } HttpURLConnection httpConn = (HttpURLConnection) connection; InputStream response; if (httpConn.getResponseCode() >= 400) { response = httpConn.getErrorStream(); } else { response = connection.getInputStream(); } String out = "{}"; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } if (!sb.toString().trim().isEmpty()) { out = sb.toString(); } } OMElement omElement = AXIOMUtil.stringToOM(out); return omElement; }
From source file:com.jiubang.core.util.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * // ww w . ja v a 2s .c o m * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); Loger.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); Loger.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; while ((line = rd.readLine()) != null) { Loger.d(LOG_TAG, line); } rd.close(); }
From source file:org.acra.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * /*from w w w . j a va2 s .c o m*/ * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); Log.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); Log.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; while ((line = rd.readLine()) != null) { Log.d(LOG_TAG, line); } rd.close(); }