List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.example.admin.processingboilerplate.JsonIO.java
public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) { try {// www. ja va 2 s . com String boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); //HttpURLConnection con = (HttpURLConnection) url.openConnection(); URLConnection uc = (url).openConnection(); HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc : (HttpURLConnection) uc; con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); con.setRequestProperty("User-Agent", USER_AGENT); OutputStream outputStream = con.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(json.toString()).append(CRLF); writer.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF); writer.close(); int status = con.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { StringBuilder sb = load(con); try { json = new JSONObject(sb.toString()); return json; } catch (JSONException e) { Log.e("loadJson", e.getMessage(), e); e.printStackTrace(); return new JSONObject(); } } else { throw new IOException("Server returned non-OK status: " + status); } } catch (IOException e) { e.printStackTrace(); } return new JSONObject(); }
From source file:Main.IrcBot.java
public static void postRequest(String pasteCode, PrintWriter out) { try {/*from ww w. j a va 2 s .c om*/ String url = "http://pastebin.com/raw.php?i=" + pasteCode; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = ""; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine + "\n"); } in.close(); //print result System.out.println(response.toString()); if (response.length() > 0) { IrcBot.postGit(response.toString(), out); } else { out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid."); } } catch (Exception p) { } }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void SendNotification(int userId, int notificationCounter) { String msg[] = new String[2]; if (notificationCounter > 1) msg = new String[] { "Tienes " + notificationCounter + " nuevas notificaciones.", "/topics/" + userId }; else//from w w w. j a v a 2s.co m msg = new String[] { "Tienes " + notificationCounter + " nueva notificacion.", "/topics/" + userId }; if (msg.length < 1 || msg.length > 2 || msg[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println( "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and // where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", msg[0].trim()); // Where to send GCM message. if (msg.length > 1 && msg[1] != null) { jGcmData.put("to", msg[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); 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); updateNotificationAsSent(userId); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); log.error(e.getMessage()); e.printStackTrace(); } }
From source file:Main.java
private static void post(String endpoint, Map<String, String> params) throws IOException { URL url;//w w w . j a v a 2s . com try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Map.Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { Log.e("URL", "> " + url); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:neal.http.impl.httpstack.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, HttpErrorCollection.AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true);/*from w ww . ja v a 2 s . c om*/ connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
From source file:com.android.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true);//from w w w .j a va 2s . co m connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
From source file:com.surfs.storage.common.util.HttpUtils.java
public static String invokeHttpForGet(String path, String... agrs) throws IOException { URL url = new URL(path); LogFactory.info("rest url:" + url.toString()); HttpURLConnection con = null; try {/* ww w .j ava2s.c om*/ con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(10000); con.setReadTimeout(1000 * 60 * 30); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); for (String string : agrs) { con.setRequestProperty("Content-type", "application/json"); con.setRequestMethod("POST"); OutputStream out = con.getOutputStream(); out.write(string.getBytes("UTF-8")); } if (con.getResponseCode() != 200) throw new ConnectException(con.getResponseMessage()); InputStream is = con.getInputStream(); return readResponse(is); } catch (IOException e) { throw e; } finally { if (con != null) { con.disconnect(); } } }
From source file:controllers.base.Application.java
public static Result login(String redirectTo, boolean isGuest) { if (isGuest) { createWebSession();// ww w.jav a 2s. c o m } else { String token = request().body().asFormUrlEncoded().get("token")[0]; String apiKey = Play.application().configuration().getString("rpx.apiKey"); String data; String response = null; try { data = String.format("token=%s&apiKey=%s&format=json", URLEncoder.encode(token, "UTF-8"), URLEncoder.encode(apiKey, "UTF-8")); URL url = new URL("https://rpxnow.com/api/v2/auth_info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw.write(data); osw.close(); response = IOUtils.toString(conn.getInputStream()); } catch (IOException e) { throw new IllegalArgumentException(e); } JsonNode profile = Json.parse(response).path("profile"); String identifier = profile.path("identifier").asText(); WebUser user = WebUser.find.where().like("providerId", identifier).findUnique(); if (user == null) { user = new WebUser().setProviderId(identifier).setProfile(Json.stringify(profile)); user.save(); } createWebSession(user); } return postLoginRedirect(redirectTo); }
From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java
private static void writeParamsToHttpPost(final HttpURLConnection conn, final List<NameValuePair> nameValuePairs) throws IOException { OutputStream out = null;// w ww. j a v a2 s . com try { out = conn.getOutputStream(); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(out, Utils.STRING_ENCODING)); writer.write(getPostDataBytes(nameValuePairs)); writer.flush(); } finally { if (writer != null) { writer.close(); } } } finally { if (out != null) { try { out.close(); } catch (final IOException e) { Log.error("writeParamsToHttpPost(): Exception while closing out", e); } } } }
From source file:RemoteDeviceDiscovery.java
public static void postDevice(RemoteDevice d) throws Exception { String url = "http://bluetoothdatabase.com/datacollection/"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "blucat"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = deviceJson(d); // Send post request con.setDoOutput(true);/*from w ww .ja v a 2s .c o m*/ DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); }