Example usage for javax.net.ssl HttpsURLConnection getContentType

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

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Returns the value of the content-type header field.

Usage

From source file:com.clearcenter.mobile_demo.mdRest.java

static private StringBuffer ProcessRequest(HttpsURLConnection http) throws IOException {
    http.connect();//from  w w w. j av a  2s  . c  o  m

    Log.d(TAG, "Result code: " + http.getResponseCode() + ", content type: " + http.getContentType()
            + ", content length: " + http.getContentLength());

    // Read response, 8K buffer
    BufferedReader buffer = new BufferedReader(new InputStreamReader(http.getInputStream()), 8192);

    String data;
    StringBuffer response = new StringBuffer();
    while ((data = buffer.readLine()) != null)
        response.append(data);

    Log.d(TAG, "Response buffer length: " + response.length());

    buffer.close();
    http.disconnect();

    return response;
}

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);
    }/* w w  w .  j  ava2s.c o 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:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String convertStream(HttpsURLConnection connection) throws IOException {
    InputStream input = connection.getInputStream();
    if (input == null) {
        return "";
    }/*  w  ww .  ja v a 2  s.c o  m*/

    InputStream readerStream;
    if (StringUtils.equalsIgnoreCase(connection.getContentEncoding(), "gzip")) {
        readerStream = new GZIPInputStream(connection.getInputStream());
    } else {
        readerStream = input;
    }
    String contentType = connection.getContentType();
    String charSet = null;
    if (contentType != null) {
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            charSet = m.group(1).trim().toUpperCase();
        }
    }

    Scanner inputScanner = StringUtils.isEmpty(charSet)
            ? new Scanner(readerStream, StandardCharsets.UTF_8.name())
            : new Scanner(readerStream, charSet);
    Scanner scannerWithoutDelimiter = inputScanner.useDelimiter("\\A");
    String result = scannerWithoutDelimiter.hasNext() ? scannerWithoutDelimiter.next() : null;
    inputScanner.close();
    scannerWithoutDelimiter.close();
    input.close();
    if (result == null) {
        result = "";
    }
    return result;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/*w w w .ja  v a 2 s.  c  o m*/
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.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");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * /*from w ww .j  a  va 2s .c  o m*/
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/*  www. ja  va  2s . co m*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}