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:Main.IrcBot.java

public static void postGit(String pasteBinSnippet, PrintWriter out) {
    try {/* www.  j av  a2 s.c om*/
        String url = "https://api.github.com/gists";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        JSONObject x = new JSONObject();
        JSONObject y = new JSONObject();
        JSONObject z = new JSONObject();
        z.put("content", pasteBinSnippet);
        y.put("index.txt", z);
        x.put("public", true);
        x.put("description", "LPBOT");
        x.put("files", y);
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "public=true&description=LPBOT";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(x.toString());
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        JSONObject gitResponse = new JSONObject(response.toString());
        String newGitUrl = gitResponse.getString("html_url");

        if (newGitUrl.length() > 0) {
            out.println("PRIVMSG #learnprogramming :The paste on Git: " + newGitUrl);
        }
        System.out.println(newGitUrl);
    } catch (Exception p) {

    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];//from  w ww  . j a  va2s .  c  o  m
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

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

@Override
public CommandResult getReply(String params, Message message, String myName) {
    try {// w w w.  j a  va2s  .com
        URL url = new URL("https://api.whatdoestrumpthink.com/api/v1/quotes/random");
        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);
            return new CommandResult(resultJson.getString("message"));
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Sends an HTTPS POST request and returns the response
 *
 * @param conn    the HTTPS connection object
 * @param payload the payload for the POST request
 * @return the response from the remote server
 *
 *///from  w  w w  .  ja  va2 s . c  om
public static int sendPost(HttpsURLConnection conn, String payload) {
    OutputStream outputStream = null;
    DataOutputStream wr = null;
    InputStream is = null;
    int response = 0;
    logger.debug("Attempting HTTPS POST...");
    try {
        outputStream = conn.getOutputStream();
        wr = new DataOutputStream(outputStream);
        wr.write(payload.getBytes("UTF-8"));
        wr.flush();
        is = conn.getInputStream();
        response = conn.getResponseCode();
    } catch (IOException e) {
        logger.debug("IOException when attempting to send a post message. ");
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an input stream. ");
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close an output stream. ");
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                logger.debug("IOException when attempting to close a data output stream. ");
            }
        }
    }
    logger.debug("HTTPS POST Response: " + response);
    return response;
}

From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithSSL.java

@Test
public void testPing() throws Exception {
    final URL url = new URL("https://" + SentryServiceIntegrationBase.SERVER_HOST + ":"
            + SentryServiceIntegrationBase.webServerPort + "/ping");
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.trustStore", Resources.getResource("cacerts.jks").getPath());
    System.setProperties(systemProps);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    Assert.assertEquals(HttpsURLConnection.HTTP_OK, conn.getResponseCode());
    String response = IOUtils.toString(conn.getInputStream());
    Assert.assertEquals("pong\n", response);
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithSSL.java

@Test
public void testPing() throws Exception {
    final URL url = new URL("https://" + SERVER_HOST + ":" + webServerPort + "/ping");
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.trustStore", Resources.getResource("cacerts.jks").getPath());
    System.setProperties(systemProps);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    Assert.assertEquals(HttpsURLConnection.HTTP_OK, conn.getResponseCode());
    String response = IOUtils.toString(conn.getInputStream());
    Assert.assertEquals("pong\n", response);
}

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

@Override
public CommandResult getReply(String params, Message message, String myName) {
    CommandResult result = new CommandResult();
    try {//from  www. j a v  a 2  s.  c o  m
        String urlString = "https://pixabay.com/api/" + "?key=" + BotConfig.getInstance().getPixabayToken()
                + "&pretty=false";
        if (params != null)
            urlString += "&q=" + URLEncoder.encode(params, "UTF-8");
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        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 totalHits = resultJson.getInt("totalHits");
            if (totalHits < 1) {
                result.replyToId = message.getMessageId();
                result.text = "No results found.";
                return result;
            }
            int pageNumber = 1;
            if (totalHits > 20) // Generate a valid page number.
                pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 15)) + 1;
            if (pageNumber > 1) {
                urlString += "&page=" + pageNumber;
                url = new URL(urlString);
                con = (HttpsURLConnection) url.openConnection();
                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 hits = resultJson.getJSONArray("hits");
            int imageIndex = Main.Random.nextInt(hits.length());
            JSONObject img = hits.getJSONObject(imageIndex);
            result.imageUrl = img.getString("webformatURL");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:fr.qinder.api.APIGetter.java

protected InputStream getInputStream(HttpsURLConnection request) throws IOException {
    InputStream res;//from   ww w .  j  ava 2s . c  om

    if (request.getResponseCode() == HttpStatus.SC_OK) {
        res = request.getInputStream();
    } else {
        res = request.getErrorStream();
    }
    return res;
}

From source file:com.github.dfa.diaspora_android.service.FetchPodsService.java

private void getPods() {
    AsyncTask<Void, Void, DiasporaPodList> getPodsAsync = new AsyncTask<Void, Void, DiasporaPodList>() {
        @Override/*  w ww . ja va  2  s.  c o m*/
        protected DiasporaPodList doInBackground(Void... params) {
            StringBuilder sb = new StringBuilder();
            BufferedReader br = null;
            try {
                HttpsURLConnection con = NetCipher.getHttpsURLConnection(PODDY_PODLIST_URL);
                if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                    // Parse JSON & return pod list
                    JSONObject json = new JSONObject(sb.toString());
                    return new DiasporaPodList().fromJson(json);
                } else {
                    AppLog.e(this, "Failed to download list of pods");
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException ignored) {
                    }
                }
            }

            // Could not fetch list of pods :(
            return new DiasporaPodList();
        }

        @Override
        protected void onPostExecute(DiasporaPodList pods) {
            if (pods == null) {
                pods = new DiasporaPodList();
            }
            Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED);
            broadcastIntent.putExtra(EXTRA_PODLIST, pods);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
            stopSelf();
        }
    };
    getPodsAsync.execute();
}

From source file:xyz.karpador.godfishbot.commands.MLPCommand.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 {//from   ww  w . j  a  v  a2 s .c o m
        String urlString = "https://derpibooru.org/search.json?q="
                + URLEncoder.encode(params, "UTF-8").replace("%20", "+");
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        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 totalHits = resultJson.getInt("total");
            if (totalHits < 1) {
                result.replyToId = message.getMessageId();
                result.text = "No results found.";
                return result;
            }
            int pageNumber = 1;
            if (totalHits > 20) // Generate a valid page number.
                pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 20)) + 1;
            if (pageNumber > 1) {
                urlString += "&page=" + pageNumber;
                url = new URL(urlString);
                con = (HttpsURLConnection) url.openConnection();
                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 hits = resultJson.getJSONArray("search");
            int imageIndex = Main.Random.nextInt(hits.length());
            JSONObject img = hits.getJSONObject(imageIndex);
            result.imageUrl = "https:" + img.getString("image");
            if (result.imageUrl.toLowerCase().endsWith(".gif"))
                result.isGIF = true;
            if (knownImages.containsKey(result.imageUrl))
                result.mediaId = knownImages.get(result.imageUrl);
            result.text = "From derpibooru.org";
            //+ "(Source: " + img.getString("source_url") + ")";
            if (!img.isNull("source_url"))
                result.text += " (Source: " + img.getString("source_url") + ")";
        } else {
            result.text = "derpibooru.org returned error code " + con.getResponseCode() + ": "
                    + con.getResponseMessage();
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}