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:org.openhab.binding.amazonechocontrol.internal.AccountServlet.java

void handleProxyRequest(Connection connection, HttpServletResponse resp, String verb, String url,
        @Nullable String referer, @Nullable String postData, boolean json, String site) throws IOException {
    HttpsURLConnection urlConnection;
    try {//from w w w . j  a va2  s .  c om
        Map<String, String> headers = null;
        if (referer != null) {
            headers = new HashMap<String, String>();
            headers.put("Referer", referer);
        }

        urlConnection = connection.makeRequest(verb, url, postData, json, false, headers);
        if (urlConnection.getResponseCode() == 302) {
            {
                String location = urlConnection.getHeaderField("location");
                if (location.contains("/ap/maplanding")) {

                    try {
                        connection.registerConnectionAsApp(location);
                        account.setConnection(connection);
                        handleDefaultPageResult(resp, "Login succeeded", connection);
                        this.connectionToInitialize = null;
                        return;
                    } catch (URISyntaxException | ConnectionException e) {
                        returnError(resp, "Login to '" + connection.getAmazonSite() + "' failed: "
                                + e.getLocalizedMessage());
                        this.connectionToInitialize = null;
                        return;
                    }

                }

                String startString = "https://www." + connection.getAmazonSite() + "/";
                String newLocation = null;
                if (location.startsWith(startString) && connection.getIsLoggedIn()) {
                    newLocation = servletUrl + PROXY_URI_PART + location.substring(startString.length());
                } else if (location.startsWith(startString)) {
                    newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
                } else {
                    startString = "/";
                    if (location.startsWith(startString)) {
                        newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
                    }
                }
                if (newLocation != null) {
                    logger.debug("Redirect mapped from {} to {}", location, newLocation);

                    resp.sendRedirect(newLocation);
                    return;
                }
                returnError(resp, "Invalid redirect to '" + location + "'");
                return;
            }
        }
    } catch (URISyntaxException | ConnectionException e) {
        returnError(resp, e.getLocalizedMessage());
        return;
    }
    String response = connection.convertStream(urlConnection);
    returnHtml(connection, resp, response, site);
}

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 {//from w w w .  ja  v a  2s .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.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java

private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception {
    /**/*from   ww w.ja  v  a  2  s.  c  om*/
     * A new connection to the endpoint that processes requests for refreshing the access token
     */
    HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL))
            .openConnection();
    refreshTokenConnection.setDoOutput(true);
    refreshTokenConnection.setRequestMethod("POST");
    refreshTokenConnection.setDoInput(true);
    refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE);
    refreshTokenConnection.connect();
    OutputStream refreshTokenRequestStream = null;
    try {
        refreshTokenRequestStream = refreshTokenConnection.getOutputStream();
        String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID,
                TOKEN_REFRESH_REDIRECT_URL, refreshToken);
        refreshTokenRequestStream.write(requestBody.getBytes());
        refreshTokenRequestStream.flush();
    } finally {
        if (refreshTokenRequestStream != null) {
            refreshTokenRequestStream.close();
        }
    }
    if (refreshTokenConnection.getResponseCode() == 200) {
        return parseRefreshTokenResponse(refreshTokenConnection);
    } else {
        throw new Exception("The attempt to refresh the access token failed");
    }
}

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

public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;//  w  w w.  j a v  a2s.  com
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        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();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.wso2telco.gsma.authenticators.mepin.MePinQuery.java

/**
 * Post request./*from w  ww.  j a  v  a2  s  .c o m*/
 *
 * @param url     the url
 * @param query   the query
 * @param charset the charset
 * @return the string
 * @throws IOException                  Signals that an I/O exception has occurred.
 * @throws XPathExpressionException     the x path expression exception
 * @throws SAXException                 the SAX exception
 * @throws ParserConfigurationException the parser configuration exception
 */
private String postRequest(String url, String query, String charset)
        throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {

    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

    ReadMobileConnectConfig readMobileConnectConfig = new ReadMobileConnectConfig();
    Map<String, String> readMobileConnectConfigResult;
    readMobileConnectConfigResult = readMobileConnectConfig.query("MePIN");
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
    connection.setRequestProperty("Authorization", "Basic " + readMobileConnectConfigResult.get("AuthToken"));
    //        connection.setRequestProperty("Authorization", "Basic "+mePinConfig.getAuthToken());

    OutputStream output = connection.getOutputStream();
    String responseString = "";

    output.write(query.getBytes(charset));

    int status = connection.getResponseCode();

    if (log.isDebugEnabled()) {
        log.debug("MePIN Response Code :" + status);
    }

    try {
        switch (status) {
        case 200:
        case 201:
        case 400:
        case 403:
        case 404:
        case 500:
            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();
            break;
        }
    } catch (Exception httpex) {
        if (connection.getErrorStream() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            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);
    }
    return responseString;
}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

/**
 * ??HTTPS GET/*from ww w.j a v a2s  .  c o  m*/
 * 
 * @param url URL
 * @return 
 */
public static HttpResp doHttpsGet(URL url) {

    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    Reader reader = null;

    try {
        // ???httphttps
        String protocol = url.getProtocol();
        if (!PROTOCOL_HTTPS.equals(protocol)) {
            throw new XinException("xin.error.url", "?https");
        }

        // 
        conn = (HttpsURLConnection) url.openConnection();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, tmArr, new SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        // ?
        conn.setConnectTimeout(connTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        // UserAgent
        conn.setRequestProperty("User-Agent", "java-sdk");

        // ?
        conn.connect();

        // ?
        inputStream = conn.getInputStream();
        reader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            stringBuilder.append(inputLine);
            stringBuilder.append("\n");
        }

        // 
        HttpResp resp = new HttpResp();
        resp.setStatusCode(conn.getResponseCode());
        resp.setStatusPhrase(conn.getResponseMessage());
        resp.setContent(stringBuilder.toString());

        // 
        return resp;
    } catch (MalformedURLException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (IOException e) {
        throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage()));
    } catch (KeyManagementException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (NoSuchAlgorithmException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } finally {

        if (reader != null) {
            try {
                reader.close();

            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", reader");
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", ?");
            }
        }

        // 
        quietClose(conn);
    }
}

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

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        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); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);/*from ww  w .jav  a 2 s .c  o m*/
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // 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();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {/*from w  ww .ja  va 2 s  .  c om*/
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *///from w  ww  . ja  va2  s .  c o m
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:com.dao.ShopThread.java

private void pay(String payurl) {
    LogUtil.debugPrintf("----------->");
    try {//w w  w. j  ava  2  s.c  om
        String postParams = getPayDynamicParams(payurl);
        HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length()));
        if (null != this.cookies) {
            loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
        }

        LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties());
        DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = loginConn.getResponseCode();
        LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl);
        LogUtil.debugPrintf("Post parameters :" + postParams);
        LogUtil.debugPrintf("Response Code : " + responseCode);
        Map<String, List<String>> header = loginConn.getHeaderFields();
        LogUtil.debugPrintf("conn.getHeaderFields():" + header);
        BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer(2000);
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String payresponse = response.toString();
        LogUtil.debugPrintf("payresponse:" + payresponse);
        List<String> cookie = header.get("Set-Cookie");
        String loginInfo;
        if (responseCode != 302) {
            LogUtil.debugPrintf("----------->");
            loginInfo = "";
        } else {
            LogUtil.debugPrintf("?----------->");
            if (null != cookie && cookie.size() > 0) {
                LogUtil.debugPrintf("cookie====" + cookie);
                setCookies(cookie);
            }
            loginInfo = "?";
        }
        LogUtil.webPrintf(loginInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}