List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java
private JSONObject post(String targetURL, JSONObject request, ProxyData proxy) throws IOException { Proxy wrappedProxy = wrapProxy(proxy); String requestValue = request.toJSONString(); HttpsURLConnection connection = null; try {//from ww w . j a v a 2s .c om URL url = new URL(targetURL); if (wrappedProxy != null) connection = (HttpsURLConnection) url.openConnection(wrappedProxy); else connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(requestValue.length())); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setReadTimeout(3000); connection.setConnectTimeout(3000); connection.connect(); /*Certificate[] certs = connection.getServerCertificates(); byte[] bytes = new byte[294]; DataInputStream dis = new DataInputStream(Session.class.getResourceAsStream("/minecraft.key")); dis.readFully(bytes); dis.close(); Certificate c = certs[0]; PublicKey pk = c.getPublicKey(); byte[] data = pk.getEncoded(); for(int i = 0; i < data.length; i++) if(data[i] != bytes[i]) throw new RuntimeException("Public key mismatch");*/ try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.writeBytes(requestValue); out.flush(); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { StringBuffer response = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { if (response.length() > 0) response.append('\n'); response.append(line); } if (response.toString().trim().isEmpty()) return null; try { JSONParser parser = new JSONParser(); Object responseObject = parser.parse(response.toString()); if (!(responseObject instanceof JSONObject)) throw new IOException("Response not type of JSONObject: " + response); return (JSONObject) responseObject; } catch (ParseException exception) { throw new IOException("Response not valid JSON: " + response, exception); } } } catch (IOException exception) { throw exception; } catch (Exception exception) { throw new IOException("Error connecting", exception); } finally { if (connection != null) connection.disconnect(); } }
From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java
private ArrayList<LatLng> fetchPlacesFromAPI(LatLng center, int radius) { ArrayList<LatLng> places = new ArrayList<>(); radius = Math.min(radius, 50000); // Max accepted radius is 50km. try {/* w w w .j a v a 2 s .c om*/ InputStream is = null; URL url = new URL(getString(R.string.places_api_url) + "?location=" + center.latitude + "," + center.longitude + "&radius=" + radius); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); // Pass package name and signature as part of request String packageName = getPackageName(); String signature = getAppSignature(); conn.setRequestProperty("X-App-Package", packageName); conn.setRequestProperty("X-App-Signature", signature); conn.connect(); int response = conn.getResponseCode(); if (response != 200) { Log.e(TAG, "Places API HTTP error: " + response + " / " + url); } else { BufferedReader reader; StringBuilder builder = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (String line; (line = reader.readLine()) != null;) { builder.append(line); } JSONArray resultsJson = (new JSONObject(builder.toString())).getJSONArray("results"); for (int i = 0; i < resultsJson.length(); i++) { JSONObject latLngJson = ((JSONObject) resultsJson.get(i)).getJSONObject("geometry") .getJSONObject("location"); places.add(new LatLng(latLngJson.getDouble("lat"), latLngJson.getDouble("lng"))); } } } catch (Exception e) { Log.e(TAG, "Exception parsing places API: " + e.toString()); } return places; }
From source file:com.gloriouseggroll.DonationHandlerAPI.java
@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" }) private JSONObject GetData(request_type type, String url, String post) { Date start = new Date(); Date preconnect = start;//from w w w. jav a 2 s.com Date postconnect = start; Date prejson = start; Date postjson = start; JSONObject j = new JSONObject("{}"); BufferedInputStream i = null; String rawcontent = ""; int available = 0; int responsecode = 0; long cl = 0; try { URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015"); c.setRequestProperty("Content-Type", "application/json-rpc"); c.setRequestProperty("Content-length", "0"); if (!post.isEmpty()) { c.setDoOutput(true); } preconnect = new Date(); c.connect(); postconnect = new Date(); if (!post.isEmpty()) { try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) { IOUtils.write(post, o); } } String content; cl = c.getContentLengthLong(); responsecode = c.getResponseCode(); if (c.getResponseCode() == 200) { i = new BufferedInputStream(c.getInputStream()); } else { i = new BufferedInputStream(c.getErrorStream()); } /* * if (i != null) { available = i.available(); * * while (available == 0 && (new Date().getTime() - * postconnect.getTime()) < 450) { Thread.sleep(500); available = * i.available(); } * * if (available == 0) { i = new * BufferedInputStream(c.getErrorStream()); * * if (i != null) { available = i.available(); } } } * * if (available == 0) { content = "{}"; } else { content = * IOUtils.toString(i, c.getContentEncoding()); } */ content = IOUtils.toString(i, c.getContentEncoding()); rawcontent = content; prejson = new Date(); j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_available", available); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); postjson = new Date(); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")"); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } if (i != null) { try { i.close(); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } } if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString()); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java
public String getUserInformation(String username, String password, String accessToken) throws AuthenticationFailedException { String responseString = ""; HttpsURLConnection connection = null; String authStr = username + ":" + password; String encoding = new String(Base64.encodeBase64(authStr.getBytes())); try {//from ww w . j a v a2 s . c om String query = String.format("access_token=%s", URLEncoder.encode(accessToken, MepinConstants.CHARSET)); connection = (HttpsURLConnection) new URL(MepinConstants.MEPIN_GET_USER_INFO_URL + "?" + query) .openConnection(); connection.setRequestMethod(MepinConstants.HTTP_GET); connection.setRequestProperty(MepinConstants.HTTP_ACCEPT, MepinConstants.HTTP_CONTENT_TYPE); connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION, MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding); int status = connection.getResponseCode(); if (log.isDebugEnabled()) { log.debug("MePIN Response Code :" + status); } if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } } else { return MepinConstants.FAILED; } } catch (IOException e) { throw new AuthenticationFailedException(MepinConstants.MEPIN_ID_NOT_FOUND, e); } finally { connection.disconnect(); } return responseString; }
From source file:org.jboss.aerogear.adm.AdmService.java
/** * Returns HttpsURLConnection that 'posts' the given payload to ADM. */// w w w .j a v a 2s. com private HttpsURLConnection post(final String registrationId, final String payload) throws Exception { final HttpsURLConnection conn = getHttpsURLConnection(registrationId); conn.setDoOutput(true); conn.setUseCaches(false); // Set the content type and accept headers. conn.setRequestProperty("content-type", "application/json"); conn.setRequestProperty("accept", "application/json"); conn.setRequestProperty("X-Amzn-Type-Version ", "com.amazon.device.messaging.ADMMessage@1.0"); conn.setRequestProperty("X-Amzn-Accept-Type", "com.amazon.device.messaging.ADMSendResult@1.0"); conn.setRequestMethod("POST"); // Add the authorization token as a header. conn.setRequestProperty("Authorization", "Bearer " + accessToken); OutputStream out = null; final byte[] bytes = payload.getBytes(UTF_8); try { out = conn.getOutputStream(); out.write(bytes); out.flush(); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; }
From source file:com.gmt2001.YouTubeAPIv3.java
@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" }) private JSONObject GetData(request_type type, String url, String post) { Date start = new Date(); Date preconnect = start;// w w w. j a v a 2s . c o m Date postconnect = start; Date prejson = start; Date postjson = start; JSONObject j = new JSONObject("{}"); BufferedInputStream i = null; String rawcontent = ""; int available = 0; int responsecode = 0; long cl = 0; try { if (url.contains("?") && !url.contains("oembed?")) { url += "&utcnow=" + System.currentTimeMillis(); } else { if (!url.contains("oembed?")) { url += "?utcnow=" + System.currentTimeMillis(); } } URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); c.setRequestProperty("Content-Type", "application/json-rpc"); c.setRequestProperty("Content-length", "0"); if (!post.isEmpty()) { c.setDoOutput(true); } preconnect = new Date(); c.connect(); postconnect = new Date(); if (!post.isEmpty()) { try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) { IOUtils.write(post, o); } } String content; cl = c.getContentLengthLong(); responsecode = c.getResponseCode(); if (c.getResponseCode() == 200) { i = new BufferedInputStream(c.getInputStream()); } else { i = new BufferedInputStream(c.getErrorStream()); } /* * if (i != null) { available = i.available(); * * while (available == 0 && (new Date().getTime() - * postconnect.getTime()) < 450) { Thread.sleep(500); available = * i.available(); } * * if (available == 0) { i = new * BufferedInputStream(c.getErrorStream()); * * if (i != null) { available = i.available(); } } } * * if (available == 0) { content = "{}"; } else { content = * IOUtils.toString(i, c.getContentEncoding()); } */ content = IOUtils.toString(i, c.getContentEncoding()); rawcontent = content; prejson = new Date(); j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_available", available); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); postjson = new Date(); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")"); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } if (i != null) { try { i.close(); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (PhantomBot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } } if (PhantomBot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString()); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java
private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) { SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword); HttpsURLConnection con = null; try {/*ww w . j a v a2 s . c om*/ con = (HttpsURLConnection) url.openConnection(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.setSSLSocketFactory(sslFactory); try { con.setRequestMethod(REQUEST_METHOD_GET); } catch (ProtocolException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION); InputStream responseStream = null; try { responseStream = (InputStream) con.getContent(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return responseStream; }
From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java
private void logout() { String url = JABLOTRON_URL + "logout"; try {/*from w w w . ja v a2s . c o m*/ URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service); connection.setRequestProperty("Cookie", session); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); setConnectionDefaults(connection); JablotronResponse response = new JablotronResponse(connection); } catch (Exception e) { //Silence //logger.error(e.toString()); } finally { controlDisabled = true; inService = false; session = ""; } return; }
From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java
private JablotronResponse sendGetStatusRequest() { String url = JABLOTRON_URL + "app/oasis/ajax/stav.php?" + getBrowserTimestamp(); try {/*from ww w. ja v a 2 s . co m*/ URL cookieUrl = new URL(url); synchronized (session) { HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Referer", JABLOTRON_URL + SERVICE_URL + service); connection.setRequestProperty("Cookie", session); connection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); setConnectionDefaults(connection); return new JablotronResponse(connection); } } catch (Exception e) { logger.error("sendGetStatusRequest exception: {}", e.toString()); return new JablotronResponse(e); } }
From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java
private Boolean refreshToken() { String url = null;/*www .j av a 2 s . c o m*/ try { //login url = ZONKY_URL + "oauth/token"; String urlParameters = "refresh_token=" + refreshToken + "&grant_type=refresh_token&scope=SCOPE_APP_WEB"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); setupConnectionDefaults(connection); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setRequestProperty("Authorization", "Basic d2ViOndlYg=="); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } String line = readResponse(connection); ZonkyTokenResponse response = gson.fromJson(line, ZonkyTokenResponse.class); token = response.getAccessToken(); refreshToken = response.getRefreshToken(); return true; } catch (MalformedURLException e) { logger.error("The URL '{}' is malformed", url, e); } catch (Exception e) { logger.error("Cannot get Zonky login token", e); } return false; }