List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:Main.java
public static String UdatePlayerBT(String userName, String device) { String retStr = ""; try {/*from w w w . j av a 2 s . com*/ URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.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("bt_device", device); 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:com.heraldapp.share.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w ww . j a va 2 s .com*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); conn.setReadTimeout(10000); conn.setConnectTimeout(10000); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } catch (SocketTimeoutException e) { return response; } return response; }
From source file:core.Web.java
public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) { // System.out.println(url); try {//from w ww .j a va 2s .co m // Create connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //connection.addRequestProperty("Authorization", API_KEY); // Set properties if needed if (properties != null && !properties.isEmpty()) { properties.forEach(connection::setRequestProperty); } // Post message if (message != null) { // Maybe somewhere connection.setDoOutput(true); // connection.setRequestProperty("Accept", "application/json"); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream()))) { writer.write(message.toString()); } } // Establish connection connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { System.err.println("Error " + responseCode + ":" + url); return null; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; String content = ""; while ((line = reader.readLine()) != null) { content += line; } return content; } } catch (IOException ex) { Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java
public static InputStream postConnection(Context context, URL url, String method, String urlParameters) throws IOException { if (!url.getProtocol().startsWith("http")) { return url.openStream(); }/*from w w w . ja v a2 s. c o m*/ URLConnection c = url.openConnection(); HttpURLConnection connection = (HttpURLConnection) c; connection.setRequestMethod(method.toUpperCase()); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); OutputStream output = null; try { output = connection.getOutputStream(); output.write(urlParameters.getBytes("UTF-8")); output.flush(); } finally { IOUtils.close(output); } return connection.getInputStream(); }
From source file:org.apache.brooklyn.util.http.HttpTool.java
/** * Closes all streams of the connection, and disconnects it. Ignores all exceptions completely, * not even logging them!//from w ww. j av a 2 s.c o m */ public static void closeQuietly(HttpURLConnection connection) { try { connection.disconnect(); } catch (Exception e) { } try { connection.getInputStream().close(); } catch (Exception e) { } try { connection.getOutputStream().close(); } catch (Exception e) { } try { connection.getErrorStream().close(); } catch (Exception e) { } }
From source file:net.cbtltd.server.WebService.java
/** * Gets the connection to the JSON server. * * @param url the connection URL./*from w w w . j a v a 2s . c o m*/ * @param rq the request object. * @return the JSON string returned by the message. * @throws Throwable the exception thrown by the method. */ private static final String getConnection(URL url, String rq) throws Throwable { String jsonString = ""; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); //connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); if (rq != null) { connection.setRequestProperty("Accept", "application/json"); connection.connect(); byte[] outputBytes = rq.getBytes("UTF-8"); OutputStream os = connection.getOutputStream(); os.write(outputBytes); } if (connection.getResponseCode() != 200) { throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url); } BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); String line; while ((line = br.readLine()) != null) { jsonString += line; } } catch (Throwable x) { throw new RuntimeException(x.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } return jsonString; }
From source file:com.binil.pushnotification.ServerUtil.java
/** * Issue a POST request to the server./*w ww.j a va 2 s . c om*/ * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException { URL url = new URL(endpoint); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setDoOutput(true); JSONObject json = new JSONObject(params); String body = json.toString(); urlConnection.setFixedLengthStreamingMode(body.length()); try { OutputStream os = urlConnection.getOutputStream(); os.write(body.getBytes("UTF-8")); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { int status = urlConnection.getResponseCode(); String connectionMsg = urlConnection.getResponseMessage(); urlConnection.disconnect(); if (status != HttpURLConnection.HTTP_OK) { Log.wtf(TAG, connectionMsg); throw new IOException("Post failed with error code " + status); } } }
From source file:com.newrelic.agent.Deployments.java
static int recordDeployment(CommandLine cmd, AgentConfig config)/* 37: */ throws Exception /* 38: */ {//from w ww .ja va 2s . com /* 39: 35 */ String appName = config.getApplicationName(); /* 40: 36 */ if (cmd.hasOption("appname")) { /* 41: 37 */ appName = cmd.getOptionValue("appname"); /* 42: */ } /* 43: 39 */ if (appName == null) { /* 44: 40 */ throw new IllegalArgumentException( "A deployment must be associated with an application. Set app_name in newrelic.yml or specify the application name with the -appname switch."); /* 45: */ } /* 46: 43 */ System.out.println("Recording a deployment for application " + appName); /* 47: */ /* 48: 45 */ String uri = "/deployments.xml"; /* 49: 46 */ String payload = getDeploymentPayload(appName, cmd); /* 50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : ""); /* 51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri); /* 52: */ /* 53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}", new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) })); /* 54: */ /* 55: */ /* 56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection(); /* 57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey()); /* 58: */ /* 59: 56 */ conn.setRequestMethod("POST"); /* 60: 57 */ conn.setConnectTimeout(10000); /* 61: 58 */ conn.setReadTimeout(10000); /* 62: 59 */ conn.setDoOutput(true); /* 63: 60 */ conn.setDoInput(true); /* 64: */ /* 65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length())); /* 66: 63 */ conn.setFixedLengthStreamingMode(payload.length()); /* 67: 64 */ conn.getOutputStream().write(payload.getBytes()); /* 68: */ /* 69: 66 */ int responseCode = conn.getResponseCode(); /* 70: 67 */ if (responseCode < 300) /* 71: */ { /* 72: 68 */ System.out.println("Deployment successfully recorded"); /* 73: */ } /* 74: 69 */ else if (responseCode == 401) /* 75: */ { /* 76: 70 */ System.out.println( "Unable to notify New Relic of the deployment because of an authorization error. Check your license key."); /* 77: 71 */ System.out.println("Response message: " + conn.getResponseMessage()); /* 78: */ } /* 79: */ else /* 80: */ { /* 81: 73 */ System.out.println("Unable to notify New Relic of the deployment"); /* 82: 74 */ System.out.println("Response message: " + conn.getResponseMessage()); /* 83: */ } /* 84: 76 */ boolean isError = responseCode >= 300; /* 85: 77 */ if ((isError) || (config.isDebugEnabled())) /* 86: */ { /* 87: 78 */ System.out.println("Response code: " + responseCode); /* 88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream(); /* 89: 81 */ if (inStream != null) /* 90: */ { /* 91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream(); /* 92: 83 */ Streams.copy(inStream, output); /* 93: */ /* 94: 85 */ PrintStream out = isError ? System.err : System.out; /* 95: */ /* 96: 87 */ out.println(output); /* 97: */ } /* 98: */ } /* 99: 90 */ return responseCode; /* 100: */ }
From source file:com.thyn.backend.gcm.GcmSender.java
public static String sendMessageToDeviceGroup(String to, String message, String sender, Long profileID, Long taskID) {//from w w w . j a va 2 s. co m String resp = null; 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", message); jData.put("sender", sender); jData.put("profileID", profileID); jData.put("taskID", taskID); // Where to send GCM message. if (to != null && message != null) { jGcmData.put("to", to.trim()); } else { Logger.logError("Error", new NullPointerException()); return null; } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://gcm-http.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); System.out.println("The payload is: " + jGcmData.toString()); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); resp = IOUtils.toString(inputStream); if (resp == null || resp.trim().equals("")) { System.out.println("Got a Null Response from the server. Unable to send GCM message."); return null; } else { System.out.println("the response from GCM server is: " + resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } JSONObject jResp = null; try { jResp = new JSONObject(resp); } catch (JSONException jsone) { jsone.printStackTrace(); } int rSuccess = jResp.getInt("success"); int rFailure = jResp.getInt("failure"); if (rSuccess == 0 && rFailure > 0) System.out.println( "Failed sending message to the recipient. Total no. of devices for the user. " + rFailure); else if (rSuccess > 0 && rFailure == 0) System.out.println("Success sending message to all receipients. Total no. of devices for the user " + rSuccess); else System.out.println("Partial success. Success sending to " + rSuccess + " devices. And failed sending to " + rFailure + " devices"); } catch (IOException e) { Logger.logError("Unable to send GCM message.", e); } return resp; }
From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, final Request<?> request) throws IOException, AuthFailureError { connection.setDoOutput(true);/* w w w . j a va 2s. c o m*/ connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); if (request instanceof MultiPartRequest) { final UploadMultipartEntity multipartEntity = ((MultiPartRequest<?>) request).getMultipartEntity(); // connection.setFixedLengthStreamingMode((int) multipartEntity.getContentLength()); multipartEntity.writeTo(connection.getOutputStream()); } else { byte[] body = request.getBody(); if (body != null) { DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }