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

The following examples show how to use javax.net.ssl.HttpsURLConnection#setRequestProperty() . 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: IntegrationTest.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPushHandlerIsProtected() throws Exception {
    String url = getAppBaseURL() + "_ah/push-handlers/receive_message";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String urlParams = "p1=a";
    byte[] postData = urlParams.getBytes( StandardCharsets.UTF_8 );
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setRequestProperty(
            "Content-Length", Integer.toString(postData.length));
    con.setRequestProperty(
            "Content-Type", "application/x-www-form-urlencoded");
    try(DataOutputStream wr = new DataOutputStream(
            con.getOutputStream())) {
        wr.write(postData);
        wr.flush();
    }
    int responseCode = con.getResponseCode();
    assertEquals(302, responseCode);
}
 
Example 2
Source File: SimpleSessionServerRequester.java    From Cleanstone with MIT License 6 votes vote down vote up
@Async(value = "mcLoginExec")
public ListenableFuture<SessionServerResponse> request(Connection connection, LoginData loginData,
                                                       PublicKey publicKey) {
    try {
        String authHash = LoginCrypto.generateAuthHash(connection.getSharedSecret(), publicKey);
        URL url = new URL(SESSION_SERVER_URL
                + String.format("?username=%s&serverId=%s&ip=%s", loginData.getPlayerName(), authHash,
                URLEncoder.encode(connection.getAddress().getHostAddress(), "UTF-8")));
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        try (Reader reader = new InputStreamReader(con.getInputStream(), Charsets.UTF_8)) {
            Gson gson = new Gson();
            return new AsyncResult<>(gson.fromJson(reader, SessionServerResponse.class));
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to contact session servers", e);
    }
}
 
Example 3
Source File: PxgridControl.java    From pxgrid-rest-ws with Apache License 2.0 6 votes vote down vote up
private HttpsURLConnection getHttpsURLConnection(String urlSuffix) throws IOException {
	String url = "https://" + config.getHostnames()[0] + ":8910/pxgrid/control/" + urlSuffix;
	URL conn = new URL(url);
	HttpsURLConnection https = (HttpsURLConnection) conn.openConnection();

	// SSL and Auth
	https.setSSLSocketFactory(config.getSSLContext().getSocketFactory());

	https.setRequestMethod("POST");

	String userPassword = config.getNodeName() + ":" + config.getPassword();
	String encoded = Base64.getEncoder().encodeToString(userPassword.getBytes());
	https.setRequestProperty("Authorization", "Basic " + encoded);
	https.setDoInput(true);
	https.setDoOutput(true);

	return https;
}
 
Example 4
Source File: Client.java    From MaterialWeCenter with Apache License 2.0 6 votes vote down vote up
private String doGet(String apiUrl) {
    try {
        // 组合链接
        Log.d("GET REQUEST", apiUrl);
        URL url = new URL(apiUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        // 附上Cookie
        connection.setRequestProperty("Cookie", cooike);
        InputStreamReader input = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(input);
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
            builder.append(line);
        String str = builder.toString();
        Log.d("GET RESPONSE", str);
        return str;
    } catch (IOException e) {
        return null;
    }
}
 
Example 5
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 6
Source File: StarsTransientMetricProvider.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private JSONObject getRemainingResource(Project project) throws IOException {
	URL url = new URL("https://api.github.com/rate_limit");
	HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
	connection.setRequestProperty("Authorization", "token " + ((GitHubRepository) project).getToken());
	connection.connect();
	InputStream is = connection.getInputStream();
	BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is, Charset.forName(UTF8)));
	String jsonText = readAll(bufferReader);
	JSONObject obj = (JSONObject) JSONValue.parse(jsonText);
	return (JSONObject) obj.get("resources");
}
 
Example 7
Source File: HttpKit.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = {new MyX509TrustManager()};
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    http.setHostnameVerifier(new TrustAnyHostnameVerifier());

    http.setConnectTimeout(25000);

    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if ((headers != null) && (!headers.isEmpty())) {
        for (Entry entry : headers.entrySet()) {
            http.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}
 
Example 8
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 9
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 10
Source File: MarketoBaseRESTClient.java    From components with Apache License 2.0 5 votes vote down vote up
public MarketoRecordResult executeGetRequest(Schema schema) throws MarketoException {
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty(REQUEST_PROPERTY_ACCEPT, REQUEST_VALUE_TEXT_JSON);
        return fillMarketoRecordResultFromReader(getReaderFromHttpResponse(urlConn), schema);
    } catch (IOException e) {
        LOG.error("Request failed: {}.", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
 
Example 11
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 12
Source File: Metrics.java    From ProRecipes 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());

    // 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 13
Source File: BStats.java    From FastAsyncWorldedit 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 void sendData(JsonObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("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 14
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 15
Source File: GeneralUtils.java    From FlareBot with MIT License 5 votes vote down vote up
/**
 * This will download and cache the image if not found already!
 *
 * @param fileUrl  Url to download the image from.
 * @param fileName Name of the image file.
 * @param user     User to send the image to.
 */
public static void sendImage(String fileUrl, String fileName, User user) {
    try {
        File dir = new File("imgs");
        if (!dir.exists() && !dir.mkdir())
            throw new IllegalStateException("Cannot create 'imgs' folder!");
        File image = new File("imgs" + File.separator + fileName);
        if (!image.exists() && image.createNewFile()) {
            URL url = new URL(fileUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 FlareBot");
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(image);
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
            is.close();
            os.close();
        }
        user.openPrivateChannel().complete().sendFile(image, fileName, null)
                .queue();
    } catch (IOException | ErrorResponseException e) {
        FlareBot.LOGGER.error("Unable to send image '" + fileName + "'", e);
    }
}
 
Example 16
Source File: Client.java    From MaterialWeCenter with Apache License 2.0 4 votes vote down vote up
private String doPost(String apiUrl, Map<String, String> params) {
    Log.d("POST REQUEST", apiUrl);
    // 建立请求内容
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey())
                .append("=")
                .append(URLEncoder.encode(entry.getValue()))
                .append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // 发出请求
    try {
        URL url = new URL(apiUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // 附上Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // 发送请求内容
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // 接收返回信息
        int response = connection.getResponseCode();
        if (response == HttpsURLConnection.HTTP_OK) {
            // 保存Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // 处理返回的字符串流
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            String str = new String(byteArrayOutputStream.toByteArray());
            Log.d("POST RESPONSE", str);
            return str;
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}
 
Example 17
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 18
Source File: Metrics.java    From UhcCore 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 19
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 20
Source File: Metrics.java    From PlayerVaults 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);
    }
}