List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:Main.java
/** * Do an HTTP POST and return the data as a byte array. *//*from w w w. j a v a2s. c om*/ public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties) throws MalformedURLException, IOException { HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(data != null); urlConnection.setDoInput(true); if (requestProperties != null) { for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) { urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue()); } } urlConnection.connect(); if (data != null) { OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(data); out.close(); } InputStream in = new BufferedInputStream(urlConnection.getInputStream()); return convertInputStreamToByteArray(in); } catch (IOException e) { String details; if (urlConnection != null) { details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage() + ")"; } else { details = ""; } Log.e("ExoplayerUtil", "executePost: Request failed" + details, e); throw e; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.thyn.backend.gcm.GcmSender.java
public static String addDeviceToDeviceGroup(String notification_key_name, String notification_key, String registration_token) { String resp = null;/*from ww w .ja va 2s .co m*/ try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); // Where to send GCM message. if (notification_key_name != null && registration_token != null) { jGcmData.put("operation", "add"); jGcmData.put("notification_key_name", notification_key_name.trim()); jGcmData.put("notification_key", notification_key.trim()); jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]")); } else { Logger.logError("Error", new NullPointerException()); return null; } // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/notification"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("project_id", SENDER_ID); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); resp = IOUtils.toString(inputStream); } catch (IOException e) { Logger.logError("Unable to add Device to Device group.", e); } return resp; }
From source file:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendPost(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;// w w w. j av a2 s . c om try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("POST"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeUTF(content); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } else { throw new IOException("Response Code: " + responseCode); } return response.toString(); } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } }
From source file:com.thyn.backend.gcm.GcmSender.java
public static String createDeviceGroup(String notification_key_name, String registration_token) { String Response_Notification_Key = null; try {/*from www. j a v a 2 s . c om*/ // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); // Where to send GCM message. if (notification_key_name != null && registration_token != null) { jGcmData.put("operation", "create"); jGcmData.put("notification_key_name", notification_key_name.trim()); jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]")); } else { Logger.logError("Error", new NullPointerException()); return null; } Logger.logInfo(jGcmData.toString()); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/notification"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("project_id", SENDER_ID); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); Logger.logInfo("the response from GCM server is: " + resp); JSONObject jResp = new JSONObject(resp); Response_Notification_Key = jResp.getString("notification_key"); } catch (IOException e) { Logger.logError("Unable to create a device group.", e); } return Response_Notification_Key; }
From source file:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendDelete(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;//w ww.j a va2s.com try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("DELETE"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeUTF(content); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } else { throw new IOException("Response Code: " + responseCode); } return response.toString(); } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } }
From source file:com.thyn.backend.gcm.GcmSender.java
public static String removeDeviceFromDeviceGroup(String notification_key_name, String notification_key, String registration_token) { String Response_Notification_Key = null; try {//from w ww. j a v a 2 s . co m // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); // Where to send GCM message. if (notification_key_name != null && registration_token != null) { jGcmData.put("operation", "remove"); jGcmData.put("notification_key_name", notification_key_name.trim()); jGcmData.put("notification_key", notification_key.trim()); jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]")); } else { Logger.logError("Error", new NullPointerException()); return null; } // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/notification"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("project_id", SENDER_ID); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); Logger.logInfo("the message sent is" + jGcmData.toString()); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); Logger.logInfo("the response from GSM server is: " + resp); JSONObject jResp = new JSONObject(resp); Response_Notification_Key = jResp.getString("notification_key"); } catch (IOException e) { Logger.logError("Unable to remove Device from Device group.", e); } return Response_Notification_Key; }
From source file:Main.java
public static String UpdateScore(String userName, int br) { String retStr = ""; try {//w w w . j a v a2 s . c om URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("broj", br); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:bluevia.SendSMS.java
public static void setFacebookWallPost(String userEmail, String post) { try {/*from www.j a va 2s . c o m*/ Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID); if (facebookAccount != null) { String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); Entity blueviaUser = Util.getUser(userEmail); //FIXME URL fbAPI = new URL( "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed"); HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection(); String content = String.format("access_token=%s&message=%s", access_key, URLEncoder.encode(post, "UTF-8")); request.setRequestMethod("POST"); request.setRequestProperty("Content-Type", "javascript/text"); request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length)); request.setDoOutput(true); request.setDoInput(true); OutputStream os = request.getOutputStream(); os.write(content.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { StringBuffer body = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) body.append(line); } while (line != null); JSONObject id = new JSONObject(body.toString()); } else log.severe( String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage())); } } catch (Exception e) { log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage())); } }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody, boolean isEncodingNeeded) throws IOException { String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )"; System.out.println(fqcn + " :: " + mn); URL restURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) restURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", userAgent); if (isEncodingNeeded) //conn.setRequestProperty("Content-Type", contentTypeURLENCODED); conn.setRequestProperty("Content-Type", contentTypeJSON); else// w w w . ja v a 2 s.co m conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8"); conn.setRequestProperty("Authorization", sessionTokens.toString()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request"); System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder jsonResponse = new StringBuilder(); while ((inputLine = in.readLine()) != null) { jsonResponse.append(inputLine); } in.close(); System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString()); return new String(jsonResponse); }
From source file:com.adr.raspberryleds.HTTPUtils.java
public static JSONObject execPOST(String address, JSONObject params) throws IOException { BufferedReader readerin = null; Writer writerout = null;/*from w w w . j a v a2 s. c o m*/ try { URL url = new URL(address); String query = params.toString(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000 /* milliseconds */); connection.setConnectTimeout(15000 /* milliseconds */); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8"); connection.addRequestProperty("Content-length", String.valueOf(query.length())); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONObject result = new JSONObject(text.toString()); if (result.has("exception")) { throw new IOException( MessageFormat.format("Remote exception: {0}.", result.getString("exception"))); } else { return result; } } else { throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}", Integer.toString(responsecode), connection.getResponseMessage())); } } catch (JSONException ex) { throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage())); } finally { if (writerout != null) { writerout.close(); writerout = null; } if (readerin != null) { readerin.close(); readerin = null; } } }