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

The following examples show how to use javax.net.ssl.HttpsURLConnection#getInputStream() . 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: MarketoBulkExecClient.java    From components with Apache License 2.0 6 votes vote down vote up
public void executeDownloadFileRequest(File filename) throws MarketoException {
    String err;
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty("accept", "text/json");
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            FileUtils.copyInputStreamToFile(inStream, filename);
        } else {
            err = String.format("Download failed for %s. Status: %d", filename, responseCode);
            throw new MarketoException(REST, err);
        }
    } catch (IOException e) {
        err = String.format("Download failed for %s. Cause: %s", filename, e.getMessage());
        LOG.error(err);
        throw new MarketoException(REST, err);
    }
}
 
Example 2
Source File: ElasticsearchQueryTest.java    From hawkular-alerts with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void directConnectionTest() throws Exception {
     SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
     URL url = new URL("https://logging-es:9200/_search");
     HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
     conn.setSSLSocketFactory(sslsocketfactory);
     InputStream inputstream = conn.getInputStream();
     InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
     BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

     String string = null;
     while ((string = bufferedreader.readLine()) != null) {
         System.out.println("Received " + string);
     }
}
 
Example 3
Source File: HttpsSocketFacTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();
    URL url = new URL("https://localhost:" + address.getPort() + "/test6614957/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    SimpleSSLSocketFactory sssf = new SimpleSSLSocketFactory();
    uc.setSSLSocketFactory(sssf);
    uc.setHostnameVerifier(new AllHostnameVerifier());
    InputStream is = uc.getInputStream();

    byte[] ba = new byte[1024];
    int read = 0;
    while ((read = is.read(ba)) != -1) {
        System.out.println(new String(ba, 0, read));
    }

    System.out.println("SimpleSSLSocketFactory.socketCreated = " + sssf.socketCreated);
    System.out.println("SimpleSSLSocketFactory.socketWrapped = " + sssf.socketWrapped);

    if (!sssf.socketCreated)
        throw new RuntimeException("Failed: Socket Factory not being called to create Socket");
}
 
Example 4
Source File: GithubImporter.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public List<Tag> getTags(String owner, String repo) throws IOException {
	List<Tag> results = new ArrayList<>();
	if (getRemainingResource("core") == 0)
		waitApiCoreRate();
	URL url = new URL("https://api.github.com/repos/" + owner + "/" + repo + "/topics?access_token=" + token);
	HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
	connection.setRequestProperty("Accept", "application/vnd.github.mercy-preview+json");
	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);
	JSONArray topics = (JSONArray) obj.get("names");
	for (Object object : topics) {
		Tag tag = new Tag();
		tag.setTag(object.toString());
		results.add(tag);
	}
	return results;
}
 
Example 5
Source File: PagarmeCalendar.java    From pagarme-java with The Unlicense 6 votes vote down vote up
private static JSONArray getPagarmeOfficialHolidayCalendar(Integer year) throws Exception {
    URL holidayCalendarURL = new URL(HOLIDAY_CALENDAR_PATH + year + ".json");
    HttpsURLConnection connection = (HttpsURLConnection) holidayCalendarURL.openConnection();
    
    String version = System.getProperty("java.version");
    int sysMajorVersion = Integer.parseInt(String.valueOf(version.charAt(2)));

    if (sysMajorVersion == 6) {
        connection.setSSLSocketFactory(new TLSSocketConnectionFactory());
    }

    connection.connect();
    Scanner scanner = new Scanner(connection.getInputStream());
    String responseJSON = scanner.useDelimiter("\\Z").next();
    scanner.close();
    JSONObject calendarJSON = new JSONObject(responseJSON);
    JSONArray holidayCalendarAsJSONArray = (JSONArray) calendarJSON.getJSONArray("calendar");

    return holidayCalendarAsJSONArray;
}
 
Example 6
Source File: NetworkTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static File httpsPage(String address) {
    try {
        URL url = new URL(address);
        File pageFile = FileTools.getTempFile(".htm");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        SSLContext sc = SSLContext.getInstance(CommonValues.HttpsProtocal);
        sc.init(null, trustAllManager(), new SecureRandom());
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(trustAllVerifier());
        connection.connect();
        try ( BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
                 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pageFile))) {
            byte[] buf = new byte[CommonValues.IOBufferLength];
            int len;
            while ((len = inStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        }
        return pageFile;
    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example 7
Source File: HttpsProxyStackOverflow.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void doClient(BadAuthProxyServer server) throws IOException {
    // url doesn't matter since we will never make the connection
    URL url = new URL("https://anythingwilldo/");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(
                  new Proxy(Proxy.Type.HTTP,
                  new InetSocketAddress("localhost", server.getPort())));
    try (InputStream is = conn.getInputStream()) {
    } catch(IOException unused) {
        // no real server, IOException is expected.
        // failure if StackOverflowError
    } finally {
        server.done();
    }
}
 
Example 8
Source File: Xkcd.java    From signal-bot with GNU Affero General Public License v3.0 5 votes vote down vote up
private File toFile(String url) throws IOException {
	HttpsURLConnection connection = (HttpsURLConnection) new URL(url.replace("http://", "https://")).openConnection();
	InputStream in = connection.getInputStream();
	File temp = File.createTempFile("xkcd", ".png");
	Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
	in.close();
	return temp;
}
 
Example 9
Source File: Utils.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
private static String executeUploadToImgur(String url, String base64, String clientKey) throws IOException {
	HttpsURLConnection conn = (HttpsURLConnection) (new URL("https://api.imgur.com/3/image")).openConnection();
	conn.addRequestProperty("Authorization", "Client-ID " + clientKey);
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestMethod("POST");
	try (OutputStream out = conn.getOutputStream()) {
		if (url != null) {
			IOUtils.write("image=" + EncodingUtil.encodeURIComponent(url) + "&type=URL", out);
		} else {
			IOUtils.write("image=" + EncodingUtil.encodeURIComponent(base64) + "&type=base64", out);
		}
		out.flush();
	}

	try (InputStream stream = conn.getInputStream()) {
		Map<String, Object> result = new ObjectMapper().readValue(stream, new TypeReference<HashMap<String,Object>>() {});
		if (result != null && result.containsKey("data")) {
			@SuppressWarnings("unchecked")
			Map<String, Object> data = (Map<String, Object>) result.get("data");
			if (data != null && data.containsKey("link")) {
				String link = (String) data.get("link");
				return "https://" + link.substring(7);
			}
		}
	} finally {
		conn.disconnect();
	}
	return null;
}
 
Example 10
Source File: EnableTLSv12.java    From tutorials with MIT License 5 votes vote down vote up
public void enableTLSv12UsingHttpConnection() throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL urls = new URL("https://" + url + ":" + port);
    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, new SecureRandom());
    HttpsURLConnection connection = (HttpsURLConnection) urls.openConnection();
    connection.setSSLSocketFactory(sslContext.getSocketFactory());
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String input;
        while ((input = br.readLine()) != null) {
            logger.info(input);
        }
    }
    logger.debug("Created TLSv1.2 connection on HttpsURLConnection");
}
 
Example 11
Source File: SessionQueryAll.java    From pxgrid-rest-ws with Apache License 2.0 5 votes vote down vote up
public static void postAndStreamPrint(HttpsURLConnection httpsConn, Object postObject) throws IOException {
	Gson gson = new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter()).create();
	httpsConn.setRequestMethod("POST");
	httpsConn.setRequestProperty("Content-Type", "application/json");
	httpsConn.setRequestProperty("Accept", "application/json");
	httpsConn.setDoInput(true);
	httpsConn.setDoOutput(true);
	OutputStreamWriter osw = new OutputStreamWriter(httpsConn.getOutputStream());
	osw.write(gson.toJson(postObject));
	osw.flush();

	int status = httpsConn.getResponseCode();
	logger.info("Response status={}", status);
	
	if (status < HttpURLConnection.HTTP_BAD_REQUEST) {
		try (InputStream in = httpsConn.getInputStream()) {
			JsonReader jreader = new JsonReader(new InputStreamReader(in));
			jreader.beginObject();
			String name = jreader.nextName();
			if ("sessions".equals(name)) {
				int count = 0;
				jreader.beginArray();
				while (jreader.hasNext()) {
					Session session = gson.fromJson(jreader, Session.class);
					System.out.println("session=" + session);
					count++;
				}
				System.out.println("count=" + count);
			}
		}
	} else {
		try (InputStream in = httpsConn.getErrorStream()) {
			String content = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println("Content: " + content);
		}
	}
}
 
Example 12
Source File: TestPhases.java    From testgrid with Apache License 2.0 5 votes vote down vote up
private JenkinsJob getLastJob(URL url, String authHeader) throws Exception {

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestProperty("Authorization", authHeader);
        con.setRequestMethod("GET");
        con.setDoOutput(true);
        SSLSocketFactory sslSocketFactory = createSslSocketFactory();
        con.setSSLSocketFactory(sslSocketFactory);

        StringBuffer response;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
        JSONObject responseObj = new JSONObject(response.toString());
        JenkinsJob jenkinsJob;
        if (responseObj.getBoolean("building")) {
            jenkinsJob = new JenkinsJob(responseObj.getString("url"), responseObj.getString("id"),
                    responseObj.getBoolean("building"));
        } else {
            jenkinsJob = new JenkinsJob(responseObj.getString("url"), responseObj.getString("result"),
                    responseObj.getString("id"), responseObj.getBoolean("building"));
        }
        con.disconnect();
        return jenkinsJob;
    }
 
Example 13
Source File: Tex.java    From signal-bot with GNU Affero General Public License v3.0 5 votes vote down vote up
private File toFile(String url) throws IOException {
	HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
	InputStream in = connection.getInputStream();
	File temp = File.createTempFile("tex", ".png");
	Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
	in.close();
	return temp;
}
 
Example 14
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 15
Source File: Metrics.java    From skript-yaml 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 16
Source File: MarkOrVerifyPin.java    From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Void doInBackground(MarkData... params) {
    Location l = params[0].loc;
    String username = params[0].username;
    Context context = params[0].context;
    Activity activity = params[0].activity;
    if( username.length() == 0 )
        return null;
    if( l == null ) {
        Log.d("Marking", "Location was null!");
        return null; // Location data isn't available yet!
    }
    try {
        List<AbstractMap.SimpleEntry> httpParams = new ArrayList<AbstractMap.SimpleEntry>();
        httpParams.add(new AbstractMap.SimpleEntry<>("username", username));
        httpParams.add(new AbstractMap.SimpleEntry<>("latitude", Double.valueOf(l.getLatitude()).toString()));
        httpParams.add(new AbstractMap.SimpleEntry<>("longitude", Double.valueOf(l.getLongitude()).toString()));

        // Vibrate once, let the user know we received the button tap
        Vibrate.pulse(context);

        URL url = new URL("https://" + Constants.DOMAIN + "/markPin");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        try {

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

            writer.write(getQuery(httpParams));
            writer.flush();
            writer.close();
            os.close();

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

            handleResponse(response, context, activity);

            Log.d("Marking", "Marked new pin, got response: " + response);
        } finally {
            conn.disconnect();
        }
    } catch( Exception e ) {
        Log.e("MarkPin", "Error marking pin: " + e.getMessage());
        Log.e("MarkPin", Log.getStackTraceString(e));
    }
    return null;
}
 
Example 17
Source File: Metrics.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) {
        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: 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 19
Source File: ApiMetricsLite.java    From Item-NBT-API 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) {
		logger.info("[NBTAPI][BSTATS] Sent data to bStats and received response: " + builder.toString());
		// 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: Metrics.java    From IridiumSkyblock with GNU General Public License v2.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());
    }
}