Example usage for javax.net.ssl HttpsURLConnection getHeaderFields

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

Introduction

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

Prototype

public Map<String, List<String>> getHeaderFields() 

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

From source file:it.serverSystem.HttpsTest.java

/**
 * SSF-13 HttpOnly flag//from w  w  w .  jav  a2  s. com
 * SSF-16 Secure flag
 */
private void checkCookieFlags(HttpsURLConnection connection) {
    List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
    boolean foundSessionCookie = false;
    for (String cookie : cookies) {
        if (StringUtils.containsIgnoreCase(cookie, "JSESSIONID")) {
            foundSessionCookie = true;
            assertThat(cookie).containsIgnoringCase("Secure").containsIgnoringCase("HttpOnly");
        }
    }
    if (!foundSessionCookie) {
        fail("Session cookie not found");
    }
}

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

void getCookies(HttpsURLConnection connection) {

    Map<String, List<String>> headerFields = connection.getHeaderFields();
    if (headerFields != null) {
        List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

        if (cookiesHeader != null) {
            for (String cookie : cookiesHeader) {
                msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }/*from ww w.  ja  v  a2  s.c  o m*/
        }
    }
}

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  ww  . ja  v  a2  s  .co m
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /* w w w  .  ja  v a 2 s. c  o m*/
 * @param strURL ?URL
 * @return jsonStr JSON??
 */
protected String sendHttpRequest(final String strURL) {
    String jsonStr = "";
    try {
        URL url = new URL(strURL);
        /*---------make and set HTTP header-------*/
        //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection();
        HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection());

        /*---------show HTTP header information-------*/
        System.out.println("\n ---------http header---------- ");
        Map headers = con.getHeaderFields();
        for (Object key : headers.keySet()) {
            System.out.println(key + ": " + headers.get(key));
        }
        con.connect();

        /*---------get HTTP body information---------*/
        String contentType = con.getHeaderField("Content-Type");
        //String charSet = "Shift-JIS";// "ISO-8859-1";
        String charSet = "UTF-8";// "ISO-8859-1";
        for (String elm : contentType.replace(" ", "").split(";")) {
            if (elm.startsWith("charset=")) {
                charSet = elm.substring(8);
                break;
            }
        }

        /*---------show HTTP body information----------*/
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet));
        } catch (Exception e_) {
            System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
            br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet));
        }
        System.out.println("\n ---------show HTTP body information----------");
        String line = "";
        while ((line = br.readLine()) != null) {
            jsonStr += line;
        }
        br.close();
        con.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(jsonStr);
    return jsonStr;
}

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

/**
 * This method performs a simple HTTP request to the BOSH director and
 * returns the results/*from   w  w w.  j  a v  a  2  s .  co m*/
 *
 * @param path the path to query
 * @return a {@link BoshResponse} object with the status code, the headers and the body of the response
 * @throws BoshClientException if there are problems
 */
public BoshResponse doSimpleRequest(String path) throws BoshClientException {
    try {
        String fixedPath;
        if (path.startsWith("/")) {
            fixedPath = path;
        } else {
            fixedPath = "/" + path;
        }
        HttpsURLConnection httpsURLConnection = setupHttpsUrlConnection(fixedPath);

        int statusCode = httpsURLConnection.getResponseCode();

        String responseBody = getResponseBody(httpsURLConnection);

        Map<String, List<String>> headers = httpsURLConnection.getHeaderFields();

        BoshResponse result = new BoshResponse(statusCode, headers, responseBody);

        return result;
    } catch (IOException e) {
        throw new BoshClientException("Error performing HTTP request (more info in the cause)", e);
    }
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_token(String urlString) throws IOException {

    String token = null;// w  w  w  .ja va 2 s .  c  om
    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        List<String> cookies1 = conn.getHeaderFields().get("Set-Cookie");

        for (int g = 0; g < cookies1.size(); g++) {
            Log.i(TAG, "Cookie_list: " + cookies1.get(g).toString());
            Cookie cookie;
            String[] cook = cookies1.get(g).toString().split(";");

            String[] subcook = cook[0].split("=");
            token = subcook[1];
            Log.i(TAG, "Sub Cook: " + subcook[1]);

            // subcook[1];
        }
    }
    //conn.disconnect();
    return token;
}

From source file:com.dao.ShopThread.java

private void pay(String payurl) {
    LogUtil.debugPrintf("----------->");
    try {/*  w w  w .ja  va  2  s.c o m*/
        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();
    }
}

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  va  2  s.c  om*/
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.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * //from   w  ww .jav a 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.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTPS request using {@link HttpsURLConnection} in XML format.
 * /*  ww  w .  j  a v a2 s .c  o  m*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTPS method type (POST, PUT)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param fileName File name of the attachment to set as binary content.
 * @return RestResponse object.
 * @throws IOException
 * @throws XMLStreamException 
 */
protected RestResponse<OMElement> sendBinaryContentForXmlResponseHTTPS(String endPoint, String httpMethod,
        Map<String, String> headersMap, String fileName) throws IOException, XMLStreamException {

    HttpsURLConnection httpsConnection = writeRequestHTTPS(endPoint, httpMethod, RestResponse.XML_TYPE,
            headersMap, fileName, true);

    String responseString = readResponse(httpsConnection);

    RestResponse<OMElement> restResponse = new RestResponse<OMElement>();
    restResponse.setHttpStatusCode(httpsConnection.getResponseCode());
    restResponse.setHeadersMap(httpsConnection.getHeaderFields());

    if (responseString != null) {
        restResponse.setBody(AXIOMUtil.stringToOM(responseString));
    }

    return restResponse;
}