List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java
@Test public void testHelloWorld() throws IOException { URL obj = new URL("https://localhost:8443/helloWorlD.html"); // Intentional case mismatch HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Accept-Language", "es, fr;q=0.8, en;q=0.7"); int responseCode = con.getResponseCode(); Assert.assertEquals("Valid reponse code", 200, responseCode); String contentType = con.getHeaderField("Content-Type"); String charset = ScriptHelperImpl.GetCharsetFromContentType(contentType); Assert.assertTrue("Correct charset", charset.equalsIgnoreCase("utf-8")); try (Reader reader = new InputStreamReader(con.getInputStream(), charset)) { int aChar; StringBuilder sb = new StringBuilder(); while ((aChar = reader.read()) != -1) sb.append((char) aChar); Assert.assertTrue("Acceptable language detected", sb.toString().contains("Hola mundo")); }/*ww w . ja v a2s.c om*/ }
From source file:com.clueride.auth.Auth0ConnectionImpl.java
@Override public int makeRequest(URL auth0Url, String accessToken) throws IOException { /* Open Connection */ HttpsURLConnection connection = (HttpsURLConnection) auth0Url.openConnection(); /* Provide 'credentials' */ connection.setRequestProperty("Authorization", "Bearer " + accessToken); /* Retrieve response */ responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); if (responseCode == 200) { InputStream inputStr = connection.getInputStream(); String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding(); jsonResponse = IOUtils.toString(inputStr, encoding); LOGGER.debug(String.format("Raw JSON Response:\n%s", jsonResponse)); } else {//from w ww.ja v a2 s. c o m LOGGER.error(String.format("Unable to read response: %d %s", responseCode, responseMessage)); } return responseCode; }
From source file:xyz.karpador.godfishbot.commands.TestLoveCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (params == null) return new CommandResult("Please submit two names."); String[] names = params.split(" "); if (names.length < 2) return new CommandResult("Please submit two names."); try {//w w w . jav a 2 s. co m URL url = new URL("https://love-calculator.p.mashape.com/getPercentage" + "?fname=" + names[0] + "&sname=" + names[1]); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = names[0] + " and " + names[1] + " fit " + resultJson.getString("percentage") + "%.\n" + resultJson.getString("result"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }
From source file:org.jboss.aerogear.adm.AdmService.java
/** * Request that ADM deliver your message to a specific instance of your app. * * @param registrationId representing the unique identifier of the device * @param clientId unique ID supplied by ADM Services * @param clientSecret secret value supplied by ADM services * @param payload , a String representing the complete payload to be submitted * @throws Exception if sending the message fails *///from w w w.j a v a 2 s . co m public void sendMessageToDevice(final String registrationId, final String clientId, final String clientSecret, final String payload) throws Exception { if (accessToken == null) { accessToken = tokenService.getAuthToken(clientId, clientSecret); } // Generate the HTTPS connection for the POST request. // You cannot make a connection over plain HTTP. HttpsURLConnection conn = post(registrationId, payload); // Obtain the response code from the connection. final int responseCode = conn.getResponseCode(); // Check if we received a failure response, and if so, get the reason for the failure. if (responseCode != 200) { if (responseCode == 401) { accessToken = tokenService.getAuthToken(clientId, clientSecret); sendMessageToDevice(registrationId, clientId, clientSecret, payload); } else { String errorContent = parseResponse(conn.getErrorStream()); throw new RuntimeException(String.format("ERROR: The enqueue request failed with a " + "%d response code, with the following message: %s", responseCode, errorContent)); } } else { // The request was successful. The response contains the canonical Registration ID for the specific instance of your // app, which may be different that the one used for the request. final String responseContent = parseResponse(conn.getInputStream()); final JSONObject parsedObject = new JSONObject(responseContent); final String canonicalRegistrationId = parsedObject.getString("registrationID"); // Check if the two Registration IDs are different. if (!canonicalRegistrationId.equals(registrationId)) { // At this point the data structure that stores the Registration ID values should be updated // with the correct Registration ID for this particular app instance. } } }
From source file:org.liberty.android.fantastischmemo.downloader.cram.CramDownloadHelper.java
/** * Get the response String from an url with optional auth token. * * @param url the request url/*from ww w . java 2 s .com*/ * @param authToken the oauth auth token. * @return the response in string. */ private String getResponseString(URL url, String authToken) throws IOException { if (!Strings.isNullOrEmpty(authToken)) { // TODO: Add oauth here } HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); if (conn.getResponseCode() / 100 >= 3) { String s = new String(IOUtils.toByteArray(conn.getErrorStream())); throw new IOException( "Request: " + url + " HTTP response code is :" + conn.getResponseCode() + " Error: " + s); } return new String(IOUtils.toByteArray(conn.getInputStream()), "UTF-8"); }
From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java
protected ConfigSchema assertReturnCode(String query, SSLContext sslContext, int expectedReturnCode) throws Exception { HttpsURLConnection httpsURLConnection = openUrlConnection(C2_URL + query, sslContext); try {// w ww.jav a2 s . c o m assertEquals(expectedReturnCode, httpsURLConnection.getResponseCode()); if (expectedReturnCode == 200) { return SchemaLoader.loadConfigSchemaFromYaml(httpsURLConnection.getInputStream()); } } finally { httpsURLConnection.disconnect(); } return null; }
From source file:xyz.karpador.godfishbot.commands.QuoteCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { try {// w w w.j a va 2 s .c o m String cat = Main.Random.nextInt(2) == 0 ? "famous" : "movies"; URL url = new URL("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=" + cat + "&count=1"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); con.setReadTimeout(5000); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = "" + resultJson.getString("quote") + " - " + resultJson.getString("author"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }
From source file:com.beanstream.connection.HttpsConnector.java
/** * Provide a detailed error message when connecting to the Beanstream API fails. *//*from w w w . j a v a 2 s. c o m*/ private BeanstreamApiException handleException(Exception ex, HttpsURLConnection connection) { String message = ""; if (connection != null) { try { int responseCode = connection.getResponseCode(); message = responseCode + " " + connection.getContent().toString(); } catch (IOException ex1) { Logger.getLogger(HttpsConnector.class.getName()).log(Level.SEVERE, "Error getting response code", ex1); } } else { message = "Connection error"; } return new BeanstreamApiException(ex, message); }
From source file:com.vmware.photon.controller.deployer.deployengine.HttpFileServiceClient.java
public Callable<Integer> uploadFile(String sourceFilePath, String destinationPath, boolean shouldOverride) { checkNotNull(sourceFilePath);//from w w w . j av a 2s . c om checkNotNull(destinationPath); File sourceFile = new File(sourceFilePath); if (!sourceFile.exists() || !sourceFile.isFile()) { throw new IllegalArgumentException("Source file must exist"); } if (!destinationPath.startsWith("/tmp")) { throw new IllegalArgumentException( "Destination path must be under /tmp when no datastore is specified"); } return () -> { URL destinationURL = new URL("https", this.hostAddress, destinationPath); if (!shouldOverride) { HttpsURLConnection urlConnection = createHttpConnection(destinationURL, "HEAD"); if (urlConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) { logger.info("File {} already exists", destinationURL.toString()); return HttpsURLConnection.HTTP_OK; } } logger.info("Uploading file {} to destination URL {}", sourceFile.getAbsolutePath(), destinationURL.toString()); return performFileUpload(sourceFile, destinationURL); }; }