Example usage for javax.net.ssl HttpsURLConnection getResponseCode

List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:com.github.opengarageapp.GarageService.java

@Override
protected void onHandleIntent(Intent intent) {
    String host = application.getServerHost();
    int port = application.getServerPort();
    Intent broadcast = new Intent(intent.getAction());
    try {/*from  w  w w  .ja  va  2 s. c  o  m*/
        String protocol = SECURE ? "https" : "http";
        String baseString = protocol + "://" + host + ":" + port + "/openGarageServer/Garage/";
        HttpsURLConnection urlConnection = getRequestFromIntent(baseString, intent);
        int responseCode = urlConnection.getResponseCode();
        application.getAuthenticator().setSuccessfulConnectionMade();
        //getResponseCode or getInputStream signals to actually make the request
        if (responseCode == HttpStatus.SC_OK) {
            String responseBody = convertStreamToString(urlConnection.getInputStream());
            urlConnection.getInputStream().close();
            broadcast.putExtra(EXTRA_HTTP_RESPONSE_TEXT, responseBody);
        } else {
            broadcast.putExtra(EXTRA_HTTP_RESPONSE_TEXT, "");
        }
        Log.i(GarageService.class.getName(), "Response Code: " + responseCode);
        broadcast.putExtra(EXTRA_HTTP_RESPONSE_CODE, responseCode);
    } catch (Exception e) {
        Log.e(getClass().getName(), "Exception", e);
        broadcast.putExtra(EXTRA_HTTP_RESPONSE_CODE, -1);
        broadcast.putExtra(EXTRA_HTTP_RESPONSE_TEXT, e.getMessage());
    } finally {
        sendBroadcast(broadcast);
    }
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.java

@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(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*  ww  w . j a  v  a  2 s  . c  om*/

    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;
    StringBuilder response = new StringBuilder();

    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();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}

From source file:xyz.karpador.godfishbot.commands.WaCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    CommandResult result = new CommandResult();
    if (params != null) {
        // Get a wallpaper by search term
        try {/*  w w w .  j  av  a2  s .  co m*/
            URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth="
                    + BotConfig.getInstance().getAlphacodersToken() + "&method=search&term="
                    + URLEncoder.encode(params, "UTF-8"));
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            if (con.getResponseCode() == HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String httpResult = br.readLine();
                JSONObject resultJson = new JSONObject(httpResult);
                int totalHits = resultJson.getInt("total_match");
                if (totalHits < 1) {
                    result.replyToId = message.getMessageId();
                    result.text = "No results found.";
                    return result;
                }
                int pageNumber = 1;
                if (totalHits > 30)
                    pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 30)) + 1;
                if (pageNumber > 1) {
                    url = new URL(url.toString() + "&page=" + pageNumber);
                    con = (HttpsURLConnection) url.openConnection();
                    if (con.getResponseCode() == HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        httpResult = br.readLine();
                        resultJson = new JSONObject(httpResult);
                    }
                }
                if (resultJson.getBoolean("success")) {
                    JSONArray imgs = resultJson.getJSONArray("wallpapers");
                    JSONObject img = imgs.getJSONObject(Main.Random.nextInt(imgs.length()));
                    result.imageUrl = img.getString("url_thumb");
                    result.text = img.getString("url_page");
                } else {
                    result.text = resultJson.getString("error");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        // Get a random wallpaper
        try {
            URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth="
                    + BotConfig.getInstance().getAlphacodersToken() + "&method=random&count=1");
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            if (con.getResponseCode() == HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String httpResult = br.readLine();
                JSONObject resultJson = new JSONObject(httpResult);
                if (resultJson.getBoolean("success")) {
                    JSONObject img = resultJson.getJSONArray("wallpapers").getJSONObject(0);
                    result.imageUrl = img.getString("url_thumb");
                    result.text = img.getString("url_page");
                } else {
                    result.text = resultJson.getString("error");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return result;
}

From source file:xyz.karpador.godfishbot.commands.GofCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (params == null)
        return new CommandResult(getUsage() + "\n" + getDescription());
    CommandResult result = new CommandResult();
    try {/*ww w. ja v  a  2 s  .  co  m*/
        String urlString = "https://gifbase.com/tag/" + params + "?format=json";
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setConnectTimeout(4000);
        if (con.getResponseCode() == HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder httpResult = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                httpResult.append(line);
            JSONObject resultJson = new JSONObject(httpResult.toString());
            int pageCount = resultJson.optInt("page_count", 1);
            if (pageCount > 1) {
                int page = Main.Random.nextInt(pageCount - 1) + 1;
                if (page != resultJson.getInt("page_current")) {
                    urlString += "&p=" + page;
                    url = new URL(urlString);
                    con = (HttpsURLConnection) url.openConnection();
                    con.setConnectTimeout(4000);
                    if (con.getResponseCode() == HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        httpResult.setLength(0);
                        while ((line = br.readLine()) != null)
                            httpResult.append(line);
                        resultJson = new JSONObject(httpResult.toString());
                    }
                }
            }
            JSONArray gifs = resultJson.optJSONArray("gifs");
            if (gifs != null) {
                JSONObject gif = gifs.getJSONObject(Main.Random.nextInt(gifs.length()));
                result.imageUrl = gif.getString("url");
            } else
                return null;
        } else {
            return new CommandResult("gifbase.com responded with error code: " + con.getResponseCode() + ": "
                    + con.getResponseMessage());
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    if (result.imageUrl == null)
        return null;
    result.isGIF = true;
    return result;
}

From source file:io.siddhi.doc.gen.extensions.githubclient.ContentsResponse.java

ContentsResponse(HttpsURLConnection connection) throws IOException {
    connection.setRequestProperty("Accept", "application/vnd.githubclient.v3." + mediaType());

    status = connection.getResponseCode();
    stream = (status == 200) ? connection.getInputStream() : connection.getErrorStream();

    headers = connection.getHeaderFields();

    contentsBodyReader = null;//from   w  w w . j  ava 2s . c  o  m
}

From source file:org.wso2.security.tools.am.webapp.service.MainService.java

private JSONArray sendRequestToGetScanners(String userId, String accessToken, String path)
        throws IOException, URISyntaxException {
    URI uriToGetStaticScanners = (new URIBuilder()).setHost(GlobalProperties.getAutomationManagerHost())
            .setPort(GlobalProperties.getAutomationManagerPort()).setScheme("https").setPath(path)
            .addParameter("userId", userId).build();
    HttpsURLConnection httpsURLConnection = HttpsRequestHandler.sendRequest(uriToGetStaticScanners.toString(),
            null, null, "GET", accessToken);
    JSONArray scanners = null;// w ww.j a v a  2s.c  o m
    if (httpsURLConnection.getResponseCode() == HttpStatus.SC_OK) {
        String jsonString = HttpsRequestHandler.getResponseAsString(httpsURLConnection);
        scanners = new JSONArray(jsonString);
    }
    return scanners;
}

From source file:xyz.karpador.godfishbot.commands.RikkaCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (imgUrls == null) {
        if (fileHelper.fileExists()) {
            String fileContent = fileHelper.getReadData();
            if (fileContent != null) {
                try {
                    JSONObject fileJson = new JSONObject(fileContent);
                    JSONArray urlsData = fileJson.getJSONArray("urls");
                    imgUrls = new ArrayList<>();
                    for (int i = 0; i < urlsData.length(); i++) {
                        JSONArray values = urlsData.getJSONArray(i);
                        imgUrls.add(new String[] { values.getString(0), values.getString(1),
                                values.optString(2, null) });
                    }/* ww w . ja v a  2 s. co m*/
                } catch (JSONException e) {
                    e.printStackTrace();
                    imgUrls = null;
                }
            }
        }
        if (imgUrls == null) {
            imgUrls = new ArrayList<>();
            try {
                for (int j = 1; j < 4; j++) {
                    URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth="
                            + BotConfig.getInstance().getAlphacodersToken() + "&method=tag&id=35982&page=" + j);
                    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
                    if (con.getResponseCode() == HTTP_OK) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        String result = br.readLine();
                        JSONObject resultJson = new JSONObject(result);
                        if (resultJson.getBoolean("success")) {
                            JSONArray imgs = resultJson.getJSONArray("wallpapers");
                            for (int i = 0; i < imgs.length(); i++) {
                                JSONObject currentImg = imgs.getJSONObject(i);
                                imgUrls.add(new String[] { currentImg.getString("url_thumb"),
                                        currentImg.getString("url_image"), null });
                            }
                            writeCurrentState();
                        }
                    }
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    CommandResult result = new CommandResult();
    String[] image = imgUrls.get(Main.Random.nextInt(imgUrls.size()));
    result.imageUrl = image[0];
    result.text = image[1];
    result.mediaId = image[2];
    return result;
}

From source file:com.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//from  w  w w  .ja v  a 2s  . c om
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.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");
        urlConn.connect();
        urlConn.getOutputStream().write(postRequest);

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err
                        .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.ct855.util.HttpsClientUtil.java

private void print_https_cert(HttpsURLConnection con) {

    if (con != null) {

        try {/* w  w  w  .j av  a  2 s. c  o  m*/

            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                System.out.println("Cert Type : " + cert.getType());
                System.out.println("Cert Hash Code : " + cert.hashCode());
                System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                System.out.println("\n");
            }

        } catch (SSLPeerUnverifiedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

From source file:xyz.karpador.godfishbot.commands.FlauschCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (imgUrls == null) {
        String fileContent = fileHelper.getReadData();
        if (fileContent != null) {
            try {
                JSONObject fileJson = new JSONObject(fileContent);
                JSONArray urlsData = fileJson.getJSONArray("urls");
                imgUrls = new ArrayList<>();
                for (int i = 0; i < urlsData.length(); i++) {
                    JSONArray values = urlsData.getJSONArray(i);
                    imgUrls.add(new String[] { values.getString(0), values.optString(1, null) });
                }/* w ww .  j a v  a 2  s  .  com*/
                lastRefreshDate = new Date(fileJson.getLong("refresh_date"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    if (imgUrls == null || new Date().getTime() >= lastRefreshDate.getTime() + (24 * 3600 * 1000)) {
        imgUrls = new ArrayList<>();
        // Populate the list with pixabay URLs
        try {
            for (int j = 1; j < 10; j++) {
                URL url = new URL("https://pixabay.com/api/" + "?key="
                        + BotConfig.getInstance().getPixabayToken() + "&q=bunny"
                        + "&image_type=photo&category=animals&pretty=false" + "&page=" + j);
                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
                if (con.getResponseCode() == HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null)
                        result.append(line);
                    JSONObject resultJson = new JSONObject(result.toString());
                    JSONArray hits = resultJson.getJSONArray("hits");

                    for (int i = 0; i < hits.length(); i++) {
                        JSONObject currentImg = hits.getJSONObject(i);
                        String tags = currentImg.getString("tags");
                        if (stringContainsAny(tags, BLOCKTAGS))
                            continue;
                        imgUrls.add(new String[] { currentImg.getString("webformatURL"), null });
                    }
                    lastRefreshDate = new Date();
                    writeCurrentState();
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    CommandResult result = new CommandResult();
    String[] data = imgUrls.get(Main.Random.nextInt(imgUrls.size()));
    result.imageUrl = data[0];
    result.mediaId = data[1];
    return result;
}