Java Code Examples for javax.net.ssl.HttpsURLConnection#setRequestMethod()
The following examples show how to use
javax.net.ssl.HttpsURLConnection#setRequestMethod() .
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 TelegramChat with GNU General Public License v3.0 | 6 votes |
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 2
Source File: GoogleUriActivity.java From LocationPrivacy with GNU General Public License v3.0 | 6 votes |
@Override protected String doInBackground(Void... params) { String result = null; HttpsURLConnection connection = null; try { connection = NetCipher.getHttpsURLConnection(urlString); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); // gzip encoding seems to cause problems // https://code.google.com/p/android/issues/detail?id=24672 connection.setRequestProperty("Accept-Encoding", ""); connection.connect(); connection.getResponseCode(); // this actually makes it go result = connection.getHeaderField("Location"); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) connection.disconnect(); } return result; }
Example 3
Source File: MarketoBulkExecClient.java From components with Apache License 2.0 | 6 votes |
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 4
Source File: MCLeaks.java From LiquidBounce with GNU General Public License v3.0 | 6 votes |
private static URLConnection preparePostRequest(final String body) { try { final HttpsURLConnection connection = (HttpsURLConnection) new URL("https://auth.mcleaks.net/v1/redeem").openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201"); connection.setDoOutput(true); final DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.write(body.getBytes(StandardCharsets.UTF_8)); dataOutputStream.flush(); dataOutputStream.close(); return connection; }catch(final Exception e) { e.printStackTrace(); return null; } }
Example 5
Source File: ConnectUnitTests.java From android-java-connect-rest-sample with MIT License | 5 votes |
@BeforeClass public static void getAccessTokenUsingPasswordGrant() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException { URL url = new URL(TOKEN_ENDPOINT); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String urlParameters = String.format( "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE, URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username, password ); connection.setRequestMethod(REQUEST_METHOD); connection.setRequestProperty("Content-Type", CONTENT_TYPE); connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length)); connection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes(urlParameters); dataOutputStream.flush(); dataOutputStream.close(); connection.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JsonParser jsonParser = new JsonParser(); JsonObject grantResponse = (JsonObject)jsonParser.parse(response.toString()); accessToken = grantResponse.get("access_token").getAsString(); }
Example 6
Source File: Metrics2.java From GriefPrevention with MIT License | 5 votes |
/** * Sends the data to the bStats server. * * @param logger The used logger. * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Logger logger, JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); if (logSentData) { logger.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("Sent data to bStats and received response: {}", builder.toString()); } }
Example 7
Source File: HttpTask.java From YalpStore with GNU General Public License v2.0 | 5 votes |
public HttpTask(String url, String method) { try { connection = (HttpsURLConnection) NetworkUtil.getHttpURLConnection(url); connection.setRequestMethod(method); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Could not get content from " + url + " : " + e.getMessage()); } }
Example 8
Source File: Engine.java From acunetix-plugin with MIT License | 5 votes |
private HttpsURLConnection openConnection(String endpoint, String method, String contentType) throws IOException { URL url = new URL(endpoint); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.addRequestProperty("X-AUTH", apiKey); return connection; }
Example 9
Source File: GCMSenderBean.java From eplmp with Eclipse Public License 1.0 | 5 votes |
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: MetricsLite2.java From bStats-Metrics with GNU Lesser General Public License v3.0 | 5 votes |
/** * Sends the data to the bStats server. * * @param logger The used logger. * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Logger logger, JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); if (logSentData) { logger.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) { logger.info("Sent data to bStats and received response: {}", builder); } }
Example 11
Source File: Metrics.java From askyblock with GNU General Public License v2.0 | 5 votes |
/** * 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 12
Source File: MetricsLite.java From PlayerSQL with GNU General Public License v2.0 | 5 votes |
/** * 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: ZoomService.java From lams with GNU General Public License v2.0 | 5 votes |
private static HttpURLConnection getZoomConnection(String urlSuffix, String method, String body, ZoomApi api) throws IOException { HttpsURLConnection connection = (HttpsURLConnection) HttpUrlConnectionUtil .getConnection(ZoomConstants.ZOOM_API_URL + urlSuffix); connection.setRequestProperty("Authorization", "Bearer " + ZoomService.generateJWT(api)); switch (method) { case "PATCH": ZoomService.setRequestMethod(connection, method); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); break; case "POST": connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); break; default: connection.setRequestMethod(method); break; } if (body != null) { OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); osw.write(body); osw.flush(); osw.close(); os.close(); } return connection; }
Example 14
Source File: SendRefreshTokenAsyncTask.java From OneNoteAPISampleAndroid with Apache License 2.0 | 5 votes |
private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception { /** * A new connection to the endpoint that processes requests for refreshing the access token */ HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL)).openConnection(); refreshTokenConnection.setDoOutput(true); refreshTokenConnection.setRequestMethod("POST"); refreshTokenConnection.setDoInput(true); refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE); refreshTokenConnection.connect(); OutputStream refreshTokenRequestStream = null; try { refreshTokenRequestStream = refreshTokenConnection.getOutputStream(); String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID, TOKEN_REFRESH_REDIRECT_URL, refreshToken); refreshTokenRequestStream.write(requestBody.getBytes()); refreshTokenRequestStream.flush(); } finally { if(refreshTokenRequestStream != null) { refreshTokenRequestStream.close(); } } if(refreshTokenConnection.getResponseCode() == 200) { return parseRefreshTokenResponse(refreshTokenConnection); } else { throw new Exception("The attempt to refresh the access token failed"); } }
Example 15
Source File: Metrics.java From ClaimChunk with MIT License | 4 votes |
/** * 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: UploadToWeb.java From open-ig with GNU Lesser General Public License v3.0 | 4 votes |
/** * 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 17
Source File: Metrics.java From FastAsyncWorldedit with GNU General Public License v3.0 | 4 votes |
/** * 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: ITestHandleHttpRequest.java From nifi with Apache License 2.0 | 4 votes |
private void secureTest(boolean twoWaySsl) throws Exception { CountDownLatch serverReady = new CountDownLatch(1); CountDownLatch requestSent = new CountDownLatch(1); processor = createProcessor(serverReady, requestSent); final TestRunner runner = TestRunners.newTestRunner(processor); runner.setProperty(HandleHttpRequest.PORT, "0"); final MockHttpContextMap contextMap = new MockHttpContextMap(); runner.addControllerService("http-context-map", contextMap); runner.enableControllerService(contextMap); runner.setProperty(HandleHttpRequest.HTTP_CONTEXT_MAP, "http-context-map"); final Map<String, String> sslProperties = getServerKeystoreProperties(); sslProperties.putAll(getTruststoreProperties()); sslProperties.put(StandardSSLContextService.SSL_ALGORITHM.getName(), CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion()); useSSLContextService(runner, sslProperties, twoWaySsl ? SslContextFactory.ClientAuth.REQUIRED : SslContextFactory.ClientAuth.NONE); final Thread httpThread = new Thread(new Runnable() { @Override public void run() { try { serverReady.await(); final int port = ((HandleHttpRequest) runner.getProcessor()).getPort(); final HttpsURLConnection connection = (HttpsURLConnection) new URL("https://localhost:" + port + "/my/path?query=true&value1=value1&value2=&value3&value4=apple=orange").openConnection(); SSLContext clientSslContext; if (twoWaySsl) { // Use a client certificate, do not reuse the server's keystore clientSslContext = SslContextFactory.createSslContext(clientTlsConfiguration); } else { // With one-way SSL, the client still needs a truststore clientSslContext = SslContextFactory.createSslContext(trustOnlyTlsConfiguration); } connection.setSSLSocketFactory(clientSslContext.getSocketFactory()); connection.setDoOutput(false); connection.setRequestMethod("GET"); connection.setRequestProperty("header1", "value1"); connection.setRequestProperty("header2", ""); connection.setRequestProperty("header3", "apple=orange"); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); sendRequest(connection, requestSent); } catch (final Throwable t) { // Do nothing as HandleHttpRequest doesn't respond normally } } }); httpThread.start(); runner.run(1, false, false); runner.assertAllFlowFilesTransferred(HandleHttpRequest.REL_SUCCESS, 1); assertEquals(1, contextMap.size()); final MockFlowFile mff = runner.getFlowFilesForRelationship(HandleHttpRequest.REL_SUCCESS).get(0); mff.assertAttributeEquals("http.query.param.query", "true"); mff.assertAttributeEquals("http.query.param.value1", "value1"); mff.assertAttributeEquals("http.query.param.value2", ""); mff.assertAttributeEquals("http.query.param.value3", ""); mff.assertAttributeEquals("http.query.param.value4", "apple=orange"); mff.assertAttributeEquals("http.headers.header1", "value1"); mff.assertAttributeEquals("http.headers.header3", "apple=orange"); mff.assertAttributeEquals("http.protocol", "HTTP/1.1"); }
Example 19
Source File: HTTPGet.java From TVRemoteIME with GNU General Public License v2.0 | 4 votes |
public static String readString(String uri){ HTTPSTrustManager.allowAllSSL(); try { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, image/jxr, */*"); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); int code = conn.getResponseCode(); if (code == 200) { BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); try { int length = conn.getContentLength(); if (length < 0) { length = 4096; } CharArrayBuffer buffer = new CharArrayBuffer(length); char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); }finally { reader.close(); } } else { return null; } } catch (Exception e) { Log.e("HTTPGet", "readString", e); } finally { } return null; }
Example 20
Source File: Metrics.java From skript-yaml with MIT License | 4 votes |
/** * 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()); } }