Java Code Examples for javax.net.ssl.HttpsURLConnection#getOutputStream()

The following examples show how to use javax.net.ssl.HttpsURLConnection#getOutputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailSenderUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Send message to Webhook URL
 * 
 * @param subscription
 * @throws IOException
 */
public void sentMessageToWebhook(String webhookUrl, String message) throws IOException {
    
    Log.debug("Webhook Message : " + message);
    URL myurl = new URL(webhookUrl);
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("Content-length", String.valueOf(message.length()));
    con.setRequestProperty("Content-Type", "application/json");
    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());
    output.writeBytes(message);
    output.flush();
    output.close();

    BufferedInputStream inStream = new BufferedInputStream(con.getInputStream());
    byte[] b = new byte[256];
    inStream.read(b);
    Log.debug("Response : " + new String(b));
}
 
Example 2
Source File: BStats.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("InvitationPersistenceHandler cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 3
Source File: MarketoBulkExecClient.java    From components with Apache License 2.0 5 votes vote down vote up
public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        return (BulkImportResult) new Gson().fromJson(getReaderFromHttpResponse(urlConn), resultClass);
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
 
Example 4
Source File: Metrics.java    From WildernessTp with MIT License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 5
Source File: MineSkinAPI.java    From SkinsRestorerX with GNU General Public License v3.0 5 votes vote down vote up
private String queryURL(String url, String query, int timeout) throws IOException {
    for (int i = 0; i < 3; i++) { // try 3 times, if server not responding
        try {
            MetricsCounter.incrAPI(url);
            HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-length", String.valueOf(query.length()));
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("User-Agent", "SkinsRestorer");
            con.setConnectTimeout(timeout);
            con.setReadTimeout(timeout);
            con.setDoOutput(true);
            con.setDoInput(true);
            DataOutputStream output = new DataOutputStream(con.getOutputStream());
            output.writeBytes(query);
            output.close();
            String outstr = "";
            InputStream _is;
            try {
                _is = con.getInputStream();
            } catch (Exception e) {
                _is = con.getErrorStream();
            }
            DataInputStream input = new DataInputStream(_is);
            for (int c = input.read(); c != -1; c = input.read()) {
                outstr += (char) c;
            }
            input.close();
            return outstr;
        } catch (Exception ignored) {
        }
    }
    return "";
}
 
Example 6
Source File: AuthenticationHandler.java    From Angelia-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends a post request to the specified URL
 * 
 * @param content - The content of the body
 * @param url     - The URL of the payload
 * @param logger  - The logger where to output this
 * @return The reponse
 * @throws IOException      - If a non 2XX reponse code is received
 * @throws Auth403Exception - If 403 (rate limit) occurs
 */
private String sendPost(String content, String url, Logger logger) throws IOException, Auth403Exception {
	byte[] contentBytes = content.getBytes("UTF-8");
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
	con.setDoOutput(true);
	con.setDoInput(true);
	con.setRequestProperty("Content-Type", "application/json");
	con.setRequestProperty("Accept-Charset", "UTF-8");
	con.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));

	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.write(contentBytes, 0, contentBytes.length);
	wr.close();
	int responseCode = con.getResponseCode();
	if ((responseCode / 100) != 2) { // we want a 200 something response code
		if (responseCode == 403) {
			throw new Auth403Exception("Auth server rejected auth attempt for account " + email
					+ ". Either you are rate limited or the auth server is down");
		} else {
			throw new IOException("POST to " + url + " returned bad 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);
	}
	in.close();
	return response.toString();
}
 
Example 7
Source File: Metrics.java    From QualityArmory with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 8
Source File: SendPageCreateAsyncTask.java    From OneNoteAPISampleAndroid with Apache License 2.0 5 votes vote down vote up
private void postMultipartRequest(String endpoint) throws Exception {

		mUrlConnection = (HttpsURLConnection) ( new URL(endpoint)).openConnection();
		mUrlConnection.setDoOutput(true);
		mUrlConnection.setRequestMethod("POST");
		mUrlConnection.setDoInput(true);
		mUrlConnection.setRequestProperty("Connection", "Keep-Alive");
		mUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
		mUrlConnection.connect();
		mOutputStream = mUrlConnection.getOutputStream();
	}
 
Example 9
Source File: GCMSenderBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private void sendMessage(JsonObject message, GCMAccount gcmAccount) {

        try{
            String apiKey = CONF.getProperty("key");

            JsonObjectBuilder body = Json.createObjectBuilder();
            JsonArrayBuilder registrationIds = Json.createArrayBuilder();
            registrationIds.add(gcmAccount.getGcmId());

            body.add("registration_ids", registrationIds);
            body.add("data", message);

            URL url = new URL(GCM_URL);

            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "key="+apiKey);
            con.setRequestProperty("Content-Type","application/json; charset=utf-8");

            con.setDoOutput(true);
            con.setDoInput(true);

            OutputStreamWriter output = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            output.write(body.build().toString());
            output.flush();
            output.close();

            int responseCode = con.getResponseCode();
            String responseMessage = con.getResponseMessage();
            LOGGER.info("gcm Sender : Response code is " + responseCode);
            LOGGER.info("gcm Sender : Response message is " + responseMessage);

        }catch(IOException e){
            LOGGER.info("gcm Sender : Failed to send message :  " + message.toString());
        }

    }
 
Example 10
Source File: Metrics.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());
    if (compressedData == null) { return; }
    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 11
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Refreshes the OpenID Connect id_token
 *
 * @param clientId from client-id
 * @param refreshToken from refresh-token
 * @param clientSecret from client-secret
 * @param sslContext to support TLS with a self signed certificate in
 *     idp-certificate-authority-data
 * @param tokenURL the url for refreshing the token
 * @return
 */
private JSONObject refreshOidcToken(
    String clientId,
    String refreshToken,
    String clientSecret,
    SSLContext sslContext,
    String tokenURL) {
  try {
    URL tokenEndpoint = new URL(tokenURL);
    HttpsURLConnection https = (HttpsURLConnection) tokenEndpoint.openConnection();
    https.setRequestMethod("POST");
    if (sslContext != null) {
      https.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    // per https://tools.ietf.org/html/rfc6749#section-2.3 the secret should be a header, not in
    // the body
    String credentials =
        Base64.getEncoder()
            .encodeToString(
                new StringBuilder()
                    .append(clientId)
                    .append(':')
                    .append(clientSecret)
                    .toString()
                    .getBytes("UTF-8"));
    https.setRequestProperty(
        "Authorization", new StringBuilder().append("Basic ").append(credentials).toString());
    https.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    https.setDoOutput(true);

    String urlData =
        new StringBuilder()
            .append("refresh_token=")
            .append(URLEncoder.encode(refreshToken, "UTF-8"))
            .append("&grant_type=refresh_token")
            .toString();
    OutputStream ou = https.getOutputStream();
    ou.write(urlData.getBytes("UTF-8"));
    ou.flush();
    ou.close();

    int code = https.getResponseCode();

    if (code != HttpsURLConnection.HTTP_OK) {
      throw new RuntimeException(
          new StringBuilder()
              .append("Invalid response code for token retrieval - ")
              .append(code)
              .toString());
    }

    Scanner scanner = new Scanner(https.getInputStream(), StandardCharsets.UTF_8.name());
    String json = scanner.useDelimiter("\\A").next();

    return (JSONObject) new JSONParser().parse(json);

  } catch (Throwable t) {
    throw new RuntimeException("Could not refresh token", t);
  }
}
 
Example 12
Source File: UploadToWeb.java    From open-ig with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Upload a file from the local directory into the specified project.
 * @param username the username
 * @param password the SVN password
 * @param project the project name
 * @param filename the file
 */
static void uploadFile(String username, String password, String project, String filename) {
	try {
		
		String boundary = "----------Googlecode_boundary_reindeer_flotilla";
		
		URL u = new URL(String.format("https://%s.googlecode.com/files", project));
		HttpsURLConnection c = (HttpsURLConnection)u.openConnection();
		try {
			String up = Base64.encodeBytes(String.format("%s:%s", username, password).getBytes("UTF-8"));
			c.setRequestProperty("Authorization", "Basic " + up);
			c.setRequestProperty("Content-Type", String.format("multipart/form-data; boundary=%s", boundary));
			c.setRequestProperty("User-Agent", "Open-IG Google Code Upload 0.1");
			c.setRequestMethod("POST");
			c.setDoInput(true);
			c.setDoOutput(true);
			c.setAllowUserInteraction(false);
			
			c.connect();
			
			try (OutputStream out = c.getOutputStream()) {

				out.write(("--" + boundary + "\r\n").getBytes("ISO-8859-1"));
				out.write("Content-Disposition: form-data; name=\"summary\"\r\n\r\nUpload.\r\n".getBytes("ISO-8859-1"));

				out.write(("--" + boundary + "\r\n").getBytes("ISO-8859-1"));
				out.write(String.format("Content-Disposition: form-data; name=\"filename\"; filename=\"%s1\"\r\n", filename).getBytes("ISO-8859-1"));
				out.write("Content-Type: application/octet-stream\r\n".getBytes("ISO-8859-1"));
				out.write("\r\n".getBytes("ISO-8859-1"));
				out.write(IOUtils.load(filename));
				out.write(("\r\n\r\n--" + boundary + "--\r\n").getBytes("ISO-8859-1"));
				out.flush();
			}
			
			System.out.write(IOUtils.load(c.getInputStream()));
			
			System.out.println(c.getResponseCode() + ": " + c.getResponseMessage());
		} finally {
			c.disconnect();
		}
	} catch (IOException ex) {
		Exceptions.add(ex);
	}
}
 
Example 13
Source File: Metrics.java    From ClaimChunk with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data   The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 14
Source File: ApiMetricsLite.java    From Crazy-Crates with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        System.out.println("[NBTAPI][BSTATS] Sending data to bStats: " + data.toString());
        // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
        //plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
    
    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());
    
    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
    
    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();
    
    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
        //plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 15
Source File: Metrics.java    From TAB with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
	if (data == null) {
		throw new IllegalArgumentException("Data cannot be null");
	}
	if (logSentData) {
		plugin.getLogger().info("Sending data to bStats: " + data.toString());
	}

	HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

	// Compress the data to save bandwidth
	byte[] compressedData = compress(data.toString());

	// Add headers
	connection.setRequestMethod("POST");
	connection.addRequestProperty("Accept", "application/json");
	connection.addRequestProperty("Connection", "close");
	connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
	connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
	connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
	connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

	// Send data
	connection.setDoOutput(true);
	DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
	outputStream.write(compressedData);
	outputStream.flush();
	outputStream.close();

	InputStream inputStream = connection.getInputStream();
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

	StringBuilder builder = new StringBuilder();
	String line;
	while ((line = bufferedReader.readLine()) != null) {
		builder.append(line);
	}
	bufferedReader.close();
	if (logResponseStatusText) {
		plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
	}
}
 
Example 16
Source File: SfmtaApiCaller.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
	try {
		// Create the connection
		URL url = new URL(baseUrl);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

		// Set parameters for the connection
		con.setRequestMethod("POST"); 
		con.setRequestProperty("content-type", "application/json");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches (false);
		
		// API now uses basic authentication
		String authString = login.getValue() + ":" + password.getValue();
		byte[] authEncBytes =
				Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		con.setRequestProperty("Authorization", "Basic "
				+ authStringEnc);

		// Set the timeout so don't wait forever (unless timeout is set to 0)
		int timeoutMsec = timeout.getValue();
		con.setConnectTimeout(timeoutMsec);
		con.setReadTimeout(timeoutMsec);

		// Write the json data to the connection
		DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
		wr.writeBytes(jsonStr);
		wr.flush();
		wr.close();
		
		// Get the response
		int responseCode = con.getResponseCode();
		
		// If wasn't successful then log the response so can debug
		if (responseCode != 200) {			
			String responseStr = "";
			if (responseCode != 500) {
				// Response code indicates there was a problem so get the
				// reply in case API returned useful error message
				InputStream inputStream = con.getErrorStream();
				if (inputStream != null) {
					BufferedReader in =
							new BufferedReader(new InputStreamReader(
									inputStream));
					String inputLine;
					StringBuffer response = new StringBuffer();
					while ((inputLine = in.readLine()) != null) {
						response.append(inputLine);
					}
					in.close();
					responseStr = response.toString();
				}
			}

			// Lot that response code indicates there was a problem
			logger.error("Bad HTTP response {} when writing data to SFMTA "
					+ "API. Response text=\"{}\" URL={} json=\n{}",
					responseCode, responseStr, baseUrl, jsonStr);
		}

		// Done so disconnect just for the heck of it
		con.disconnect();
		
		// Return whether was successful
		return responseCode == 200;
	} catch (IOException e) {
		logger.error("Exception when writing data to SFMTA API: \"{}\" "
				+ "URL={} json=\n{}", 
				e.getMessage(), baseUrl, jsonStr);
		
		// Return that was unsuccessful
		return false;
	}
	
}
 
Example 17
Source File: Metrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data);
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
        outputStream.write(compressedData);
    }

    StringBuilder builder = new StringBuilder();
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line);
        }
    }

    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder);
    }
}
 
Example 18
Source File: BStatsMetricsLite.java    From Sentinel with MIT License 4 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 19
Source File: CommonUtil.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
 * 发送https请求
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return 返回微信服务器响应的信息
 */
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		return buffer.toString();
	} catch (ConnectException ce) {
		log.error("连接超时:{}", ce);
	} catch (Exception e) {
		log.error("https请求异常:{}", e);
	}
	return null;
}
 
Example 20
Source File: RequestUtils.java    From ibm-wearables-android-sdk with Apache License 2.0 4 votes vote down vote up
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException {

        URL url = new URL("https://medge.mybluemix.net/alg/train");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        JSONObject jsonToSend = createTrainBodyJSON(name,uuid,accelerometerData,gyroscopeData);


        OutputStream outputStream = conn.getOutputStream();
        DataOutputStream wr = new DataOutputStream(outputStream);
        wr.writeBytes(jsonToSend.toString());
        wr.flush();
        wr.close();

        outputStream.close();

        String response = "";

        int responseCode=conn.getResponseCode();

        //Log.e("BBB2","" + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="{}";
        }

        handleResponse(response,requestResult);
    }