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:snow.http.auth.Facebook.java

private Term fetchProfile(String accessToken) {
    try {//from  ww w .j a  v a  2 s. c  o  m

        URL url = new URL(PROFILE + accessToken);// +"&appsecret_proof="+MDigest.HmacSHA256(AppSecret,
                                                 // accessToken));

        // System.out.println(url);

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        try (InputStream stream = con.getInputStream()) {

            if (con.getResponseCode() == 200) {

                ObjectMapper mapper = new ObjectMapper();

                JsonNode root = mapper.readTree(url.openStream());

                JsonNode node = root.get("id");
                if (node != null) {
                    String fbID = node.asText();

                    //                        try (Transaction tx = Core.DB.beginTx()) {
                    //                            TermMutable term;
                    //                            Node termNode = Core.search(FACEBOOK_ID, fbID);
                    //                            if (termNode == null) {
                    //                                term = Unstable.term();
                    //
                    //                                term.property(FACEBOOK_ID, fbID);
                    //
                    //                                term.type(Primitives.PERSON);
                    //                            } else {
                    //                                term = TermInDB.term(termNode);
                    //                            }
                    //
                    //                            term.link(new URL("https://www.facebook.com/profile.php?id=" + fbID));
                    //
                    //                            for (String field : FIELDS) {
                    //                                node = root.get(field);
                    //
                    //                                if (node != null) {
                    //                                    switch (field) {
                    //                                    case "languages":
                    //                                        // XXX: code
                    //                                        break;
                    //
                    //                                    case "picture":
                    //                                        JsonNode data = node.get("data");
                    //                                        if (data != null) {
                    //                                            JsonNode picURL = data.get("url");
                    //                                            if (picURL != null) {
                    //                                                try {
                    //                                                    URL imgURL = new URL(picURL.asText());
                    //
                    //                                                    term.property("facebook:" + field, imgURL.toString());
                    //
                    //                                                    term.visual(imgURL);
                    //                                                } catch (MalformedURLException e) {
                    //                                                }
                    //                                            }
                    //                                        }
                    //
                    //                                        break;
                    //
                    //                                    case "name":
                    //                                        term.label(ORIGINAL_LANGUAGE, node.asText());
                    //
                    //                                    default:
                    //                                        term.property("facebook:" + field, node.asText());
                    //
                    //                                        break;
                    //                                    }
                    //                                }
                    //                            }
                    //
                    //                            // System.out.println("term = "+term.debug(0));
                    //
                    //                            TermInDB person = TermInDB.term(term);
                    //
                    //                            tx.success();
                    //
                    //                            return person;
                    //                        }
                }
            }
        } catch (IOException e) {
            // e.printStackTrace();
            //
            // System.out.println("response code = "+con.getResponseCode());
            //
            // try (InputStream stream = con.getErrorStream()) {
            // java.util.Scanner s = new
            // java.util.Scanner(stream).useDelimiter("\\A");
            // System.out.println(s.hasNext() ? s.next() : "");
            // }
        }

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

    return null;
}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method launches a complex query, which requires a single BOSH task
 * to be launched and completed. This method performs the query, gathers the
 * task number, waits for its completion and returns its results.
 *
 * @param path path to query//  w  w  w .  j  a  v a 2  s  .c  o  m
 * @return the results of the launched tasks
 * @throws BoshClientException if there are problems
 */
public String doComplexQuerySingleTask(String path) throws BoshClientException {
    BoshResponse initialRequestResults = doSimpleRequest(path);
    if (initialRequestResults.getStatusCode() != 302
            || !initialRequestResults.getHeaders().containsKey("Location")
            || initialRequestResults.getHeaders().get("Location").isEmpty()) {
        throw new BoshClientException(
                "Unexpected response from BOSH director. Please check whether the path leads to a single task creation. Response results are: "
                        + initialRequestResults);
    }
    String locationValue = initialRequestResults.getHeaders().get("Location").get(0);
    Pattern taskNumberPattern = Pattern.compile(REGEX_TASK_LOCATION);
    Matcher taskNumberMatcher = taskNumberPattern.matcher(locationValue);
    boolean matches = taskNumberMatcher.matches();
    if (!matches) {
        throw new BoshClientException(
                "Location header containing task number has an unexpected format: " + locationValue);
    }
    String taskNumberStr = taskNumberMatcher.group("taskNumber");
    boolean completed = false;
    while (!completed) {
        try {
            HttpsURLConnection taskRequestHttpsURLConnection = setupHttpsUrlConnection(
                    "/tasks/" + taskNumberStr);

            int taskRequestStatusCode = taskRequestHttpsURLConnection.getResponseCode();
            if (taskRequestStatusCode >= 300) {
                throw new BoshClientException(
                        "Received code " + taskRequestStatusCode + " while requesting task status.");
            }
            String taskRequestResponse = getResponseBody(taskRequestHttpsURLConnection);

            try {
                JSONObject taskJson = new JSONObject(taskRequestResponse);
                String state = taskJson.optString("state");
                if (state.equals("done")) {
                    completed = true;
                    break;
                }
            } catch (JSONException e) {

            }

        } catch (IOException e) {
            throw new BoshClientException("Error while requesting task state or results", e);
        }

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new BoshClientException("Interrupted while sleeping", e);
        }
    }

    try {
        HttpsURLConnection taskResultHttpsURLConnection = setupHttpsUrlConnection(
                "/tasks/" + taskNumberStr + "/output?type=result");
        int responseCode = taskResultHttpsURLConnection.getResponseCode();
        if (responseCode >= 300) {
            throw new BoshClientException(
                    "Unexpected " + responseCode + " response code while getting task results");
        }
        String result = getResponseBody(taskResultHttpsURLConnection);
        return result;

    } catch (IOException e) {
        throw new BoshClientException("Error while getting results", e);
    }

}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processDeleteRequest(URL url, String keyStore, String keyStorePassword)
        throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setRequestMethod("DELETE");
    con.addRequestProperty("x-ms-version", "2014-04-01");

    return con.getResponseCode();
}

From source file:com.microsoft.onenote.pickerlib.ApiRequestAsyncTask.java

private JSONObject getJSONResponse(String endpoint) throws Exception {
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) (new URL(endpoint)).openConnection();
    mUrlConnection.setRequestProperty("User-Agent",
            System.getProperty("http.agent") + " Android OneNotePicker");
    if (mAccessToken != null) {
        mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
    }//from   w w w . j a  va2  s. co m
    mUrlConnection.connect();

    int responseCode = mUrlConnection.getResponseCode();
    String responseMessage = mUrlConnection.getResponseMessage();
    String responseBody = null;
    boolean responseIsJson = mUrlConnection.getContentType().contains("application/json");
    JSONObject responseObject;
    if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
        mUrlConnection.disconnect();
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Invalid or missing access token.", null);
    }
    if (responseIsJson) {
        InputStream is = null;
        try {
            if (responseCode == HttpsURLConnection.HTTP_INTERNAL_ERROR) {
                is = mUrlConnection.getErrorStream();
            } else {
                is = mUrlConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            String lineSeparator = System.getProperty("line.separator");
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                buffer.append(lineSeparator);
            }
            responseBody = buffer.toString();
        } finally {
            if (is != null) {
                is.close();
            }
            mUrlConnection.disconnect();
        }

        responseObject = new JSONObject(responseBody);
    } else {
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Unrecognized server response", null);
    }

    return responseObject;
}

From source file:com.illusionaryone.GameWispAPI.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;/*from  w ww  . j  av  a2s.c om*/
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module.");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        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 QuorraBot/2015");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        urlConn.connect();

        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, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
            }
        }
    }

    return (jsonResult);
}

From source file:snow.http.auth.Facebook.java

@Override
public boolean handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Throwable {
    String uri = request.getUri();
    if (!uri.startsWith(ROOT))
        return false;

    if (!request.getMethod().equals(GET)) {
        HttpErrorHelper.handle(ctx, request, METHOD_NOT_ALLOWED);
        return true;
    }/*from  www . ja  va 2  s  . co m*/

    // System.out.println(uri);

    String function = uri.substring(ROOT.length());

    if (function.startsWith("facebook/")) {

        Session session = SessionRegistry._.active();

        if (session != null) {
            Long expiresAt = session.getLong(EXPIRES_AT);
            if (expiresAt != null) {
                if (expiresAt > System.currentTimeMillis()) {
                    sendRedirect(ctx, request, "/");
                    return true;
                } else {
                    session.remove(ACCESS_TOKEN);
                    session.remove(EXPIRES_AT);
                    session.remove(SUBJECT);
                }
            }
        }

        FastMap<String, String> map = new FastMap<String, String>();
        try {

            parseParams(map, function);

            if (map.containsKey("error")) {
                HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                return true;

            } else if (map.containsKey("error_code")) {
                HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                return true;

            } else if (map.containsKey("code")) {

                if (map.containsKey(STATE)) {
                    if (session != null && !map.get(STATE).equals(session.ID()._)) {
                        HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                        return true;
                    } else {
                        session = SessionRegistry._.activate(map.get(STATE));

                        // check 'state'
                        if (session == null || !map.get(STATE).equals(session.ID()._)) {
                            HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                            return true;
                        }
                    }
                } else {
                    HttpErrorHelper.handle(ctx, request, UNAUTHORIZED);
                    return true;
                }

                URL url = new URL(AUTH + map.get("code").trim());

                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

                try (InputStream stream = con.getInputStream()) {

                    if (con.getResponseCode() == 200) {

                        readAccessToken(stream);
                    }

                } catch (IOException e) {
                    HttpErrorHelper.handle(ctx, request, FORBIDDEN);
                    return true;
                }

                sendRedirect(ctx, request, "/");
                return true;
            }

            if (session == null)
                session = SessionRegistry._.make();

            sendRedirect(ctx, request, AUTHORIZE + session.ID()._);
            return true;

        } catch (Throwable e) {
            e.printStackTrace();
            HttpErrorHelper.handle(ctx, request, INTERNAL_SERVER_ERROR);
            return true;
        }

    } else {
        HttpErrorHelper.handle(ctx, request, NOT_FOUND);
        return true;
    }
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse getWithBasicAuth(String Uri, String requestParameters, String userName,
        String password) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;/*from  w  ww. jav a  2s . c  o  m*/
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static boolean sendCommand(Configuration conf, String path) throws IOException {
    setupSslProps(conf);/*w w  w  . j a  va  2  s  .c om*/
    int sslPort = getSslAddr(conf).getPort();
    int err = 0;
    StringBuilder b = new StringBuilder();

    HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), "");
    Set<String> hostsList = hostsReader.getHosts();
    for (String hostname : hostsList) {
        HttpsURLConnection connection = null;
        try {
            connection = openConnection(hostname, sslPort, path);
            connection.connect();
            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates();
                if (clientCerts != null) {
                    for (X509Certificate cert : clientCerts)
                        sb.append("\n Client certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No client certificates were found");
                }
                X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
                if (serverCerts != null) {
                    for (X509Certificate cert : serverCerts)
                        sb.append("\n Server certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No server certificates were found");
                }
                LOG.debug(sb.toString());
            }
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
                err++;
            }
        } catch (IOException e) {
            b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
            if (LOG.isDebugEnabled())
                LOG.debug("Exception happend for host " + hostname, e);
            err++;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
    if (err > 0) {
        System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:")
                + b.toString() + "\n");
        return false;
    }
    return true;
}

From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java

/**
 * Send REST call/*from   w ww .jav a  2  s .  c om*/
 */
public boolean sendRESTCall(String url, String urlParameters) throws IOException {
    HttpsURLConnection connection = null;
    try {
        URL smsProviderUrl = new URL(url + urlParameters);
        connection = (HttpsURLConnection) smsProviderUrl.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(SMSOTPConstants.HTTP_METHOD);
        if (connection.getResponseCode() == 200) {
            if (log.isDebugEnabled()) {
                log.debug("Code is successfully sent to your mobile number");
            }
            return true;
        }
        connection.disconnect();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.error("Invalid URL", e);
        }
        throw new MalformedURLException();
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while setting the HTTP method", e);
        }
        throw new ProtocolException();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while getting the HTTP response", e);
        }
        throw new IOException();
    } finally {
        connection.disconnect();
    }
    return false;
}

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;//from  www.  jav a2s .c om
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}