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

The following examples show how to use javax.net.ssl.HttpsURLConnection#setDoOutput() . 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: Metrics.java    From SubServers-2 with Apache License 2.0 6 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 {
    Validate.notNull(data, "Data cannot be null");
    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 2
Source File: Metrics.java    From TelegramChat with GNU General Public License v3.0 6 votes vote down vote up
private int sendData(String dataJson) throws Exception{
	java.net.URL obj = new java.net.URL(URL);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	con.setRequestMethod("POST");
	con.setRequestProperty("User-Agent", "Java/Bukkit");
	con.setRequestProperty("Metrics-Version", this.VERSION);

	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(dataJson);
	wr.flush();
	wr.close();
	
	return Integer.parseInt(con.getHeaderField("interval-millis"));
}
 
Example 3
Source File: MarketoBaseRESTClient.java    From components with Apache License 2.0 6 votes vote down vote up
public InputStreamReader httpFakeGet(String content, boolean isForLead) throws MarketoException {
    try {
        current_uri.append(fmtParams(QUERY_METHOD, QUERY_METHOD_GET));
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod(QUERY_METHOD_POST);
        if (isForLead) {
            urlConn.setRequestProperty(REQUEST_PROPERTY_CONTENT_TYPE, REQUEST_VALUE_APPLICATION_X_WWW_FORM_URLENCODED);
        } else {
            urlConn.setRequestProperty(REQUEST_PROPERTY_CONTENT_TYPE, REQUEST_VALUE_APPLICATION_JSON);
        }
        urlConn.setRequestProperty(REQUEST_PROPERTY_ACCEPT, REQUEST_VALUE_TEXT_JSON);
        urlConn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
        wr.write(content);
        wr.flush();
        wr.close();
        return getReaderFromHttpResponse(urlConn);
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
 
Example 4
Source File: MultiPart.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
     * Post this multipart message using the given connection.
     *
     * @param conn An HTTPS connection.
     *
     * @return A (message, location) pair; the message is the http response
     * message, location is null if the response code was not in the 200 range.
     *
     * @throws IOException if the thread is interrupted during the connection.
     */
    public Pair<String, String> post(final HttpsURLConnection conn) throws IOException {
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", BrandingUtilities.APPLICATION_NAME);
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundary());
        conn.setRequestProperty("Content-Length", Integer.toString(size()));

        try (final OutputStream os = conn.getOutputStream()) {
            os.write(getBuffer());
        }

        final int code = conn.getResponseCode();

        final String location;
        final int responseClass = code / 100;
        if (responseClass == 2) {
            location = conn.getHeaderField("Location");
        } else {
            location = null;
        }

//        conn.getHeaderFields().entrySet().stream().forEach(entry ->
//        {
//            System.out.printf("@@MultiPart header %s: %s\n", entry.getKey(), entry.getValue());
//        });
//        System.out.printf("@@MultiPart response [%s]\n", new String(getBody(conn, code)));
        return new Pair<>(conn.getResponseMessage(), location);
    }
 
Example 5
Source File: Metrics.java    From BlueMap with MIT License 5 votes vote down vote up
private static String sendData(String data) throws MalformedURLException, IOException {
	byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
	
       HttpsURLConnection connection = (HttpsURLConnection) new URL(METRICS_REPORT_URL).openConnection();
       connection.setRequestMethod("POST");
       connection.addRequestProperty("Content-Length", String.valueOf(bytes.length));
       connection.setRequestProperty("Content-Type", "application/json");
       connection.addRequestProperty("Content-Encoding", "gzip");
       connection.addRequestProperty("Connection", "close");
       connection.setRequestProperty("User-Agent", "BlueMap");
       connection.setDoOutput(true);
       
       try (OutputStream out = connection.getOutputStream()){
        out.write(bytes);
        out.flush();
       }
       
       try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
       	String line;
       	StringBuilder builder = new StringBuilder();
       	
       	while ((line = in.readLine()) != null) {
       		builder.append(line + "\n");
       	}
       	
       	return builder.toString(); 
       }
       
}
 
Example 6
Source File: MetricsLite.java    From skUtilities 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 7
Source File: GooglePhotosClient.java    From STGUploader with MIT License 5 votes vote down vote up
public void createMediaItem(String uploadToken) throws Exception{
    HttpsURLConnection connection = (HttpsURLConnection) new URL("https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate").openConnection();


    connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
    connection.setUseCaches(false);
    connection.setRequestProperty("Connection", "close");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true); // Triggers POST.

    String json = "{\n" +
            "  \"newMediaItems\": [\n" +
            "    {\n" +
            "      \"simpleMediaItem\": {\n" +
            "        \"uploadToken\": \""+uploadToken+"\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    OutputStream output = connection.getOutputStream();
    output.write(json.getBytes());
    output.flush();

    Logger.info("Response Code: " + connection.getResponseCode());
    Logger.info(getResponseString(connection));
}
 
Example 8
Source File: Metrics.java    From Modern-LWC 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 9
Source File: RandomOrgClient.java    From JSON-RPC-Java with MIT License 5 votes vote down vote up
/** POST JSON to server and return JSON response.
 ** 
 ** @param json request to post. 
 **
 ** @return JSON response.
 **
 ** @throws IOException @see java.io.IOException
 ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException
 ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received.
 **/
private JsonObject post(JsonObject json) throws IOException, MalformedURLException, RandomOrgBadHTTPResponseException {

	HttpsURLConnection con = (HttpsURLConnection) new URL("https://api.random.org/json-rpc/1/invoke").openConnection();
	con.setConnectTimeout(this.httpTimeout);

	// headers		
	con.setRequestMethod("POST");
	con.setRequestProperty("Content-Type", "application/json");
	
	// send JSON
	con.setDoOutput(true);
	DataOutputStream dos = new DataOutputStream(con.getOutputStream());
	dos.writeBytes(json.toString());
	dos.flush();
	dos.close();

	// check response
	int responseCode = con.getResponseCode();
	
	// return JSON...
	if (responseCode == HttpsURLConnection.HTTP_OK) {
		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 new JsonParser().parse(response.toString()).getAsJsonObject();
		
	// ...or throw error
	} else {
		throw new RandomOrgBadHTTPResponseException("Error " + responseCode + ": " + con.getResponseMessage());
	}
}
 
Example 10
Source File: LocationRetriever.java    From AppleWifiNlpBackend with Apache License 2.0 5 votes vote down vote up
private static void prepareConnection(HttpsURLConnection connection,
        int length) throws ProtocolException {
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty(HTTP_FIELD_CONTENT_TYPE, CONTENT_TYPE_URLENCODED);
    connection.setRequestProperty(HTTP_FIELD_CONTENT_LENGTH, String.valueOf(length));
}
 
Example 11
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 12
Source File: EvepraisalGetter.java    From jeveassets with GNU General Public License v2.0 4 votes vote down vote up
public static String post(Map<Item, Long> itemCounts) {
	DecimalFormat number  = new DecimalFormat("0");
	StringBuilder builder = new StringBuilder();
	for (Map.Entry<Item, Long> entry : itemCounts.entrySet()) {
		builder.append(entry.getKey().getTypeName());
		builder.append(" ");
		builder.append(number.format(entry.getValue()));
		builder.append("\r\n");
	}
	StringBuilder urlParameters = new StringBuilder();
	//market=jita&raw_textarea=avatar&persist=no
	urlParameters.append("market=");
	urlParameters.append(encode("jita"));
	urlParameters.append("&raw_textarea=");
	urlParameters.append(encode(builder.toString()));
	try {
		URL obj = new URL("https://evepraisal.com/appraisal.json");
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		// add request header
		con.setRequestMethod("POST");
		con.setConnectTimeout(10000);
		con.setReadTimeout(10000);

		// Send post request
		con.setDoOutput(true);
		try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
			wr.writeBytes(urlParameters.toString());
			wr.flush();
		}

		StringBuilder response;
		try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
			String inputLine;
			response = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
		}
		// read json
		Gson gson = new GsonBuilder().create();
		Result result = gson.fromJson(response.toString(), Result.class);
		return result.getID();
		// set data
	} catch (IOException | JsonParseException ex) {
		LOG.error(ex.getMessage(), ex);
	}
	return null;
}
 
Example 13
Source File: BStats.java    From DiscordSRV 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.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: CStats.java    From TabooLib with MIT License 4 votes vote down vote up
/**
 * Sends the data to the cStats 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 cStats: " + 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/" + C_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 cStats and received response: " + builder);
    }
}
 
Example 15
Source File: HttpsTrustManager.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String httpsRequest(String requestUrl, String requestMethod,
        String outputStr) {
    StringBuffer buffer = null;
    try {
        // 创建SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] tm = { new HttpsTrustManager() };
        // 初始化
        sslContext.init(null, tm, new java.security.SecureRandom());
        ;
        // 获取SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        // url对象
        URL url = new URL(requestUrl);
        // 打开连接
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        /**
         * 这一步的原因: 当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore
         * 但是服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。
         * 
         * 解决方法:让JRE相信所有的证书和对系统的域名和证书域名。
         * 
         * 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be localhost
         */
        conn.setHostnameVerifier(new HttpsTrustManager().new TrustAnyHostnameVerifier());
        // 设置一些参数
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(requestMethod);
        // 设置当前实例使用的SSLSoctetFactory
        conn.setSSLSocketFactory(ssf);
        conn.connect();
        // 往服务器端的参数
        if (null != outputStr) {
            @Cleanup
            OutputStream os = conn.getOutputStream();
            os.write(outputStr.getBytes("utf-8"));
        }
        // 读取服务器端返回的内容
        InputStream is = conn.getInputStream();
        //读取内容
        InputStreamReader isr = new InputStreamReader(is,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        buffer = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer.toString();
}
 
Example 16
Source File: Metrics.java    From TAB with Apache License 2.0 4 votes vote down vote up
private 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 17
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 18
Source File: Metrics.java    From Quests 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: 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 20
Source File: HttpTLSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    
    // parse our command line to retrieve required input
    
    CommandLine cmd = parseCommandLine(args);

    final String url = cmd.getOptionValue("url");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our http client
    
    try {
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword,
                certPath, keyPath);
        keyRefresher.startup();
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());
        
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setReadTimeout(15000);
        con.setDoOutput(true);
        con.connect();
        
        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
              sb.append(line);
            }
            System.out.println("Data output: " + sb.toString());
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}