Example usage for java.net HttpURLConnection getHeaderFields

List of usage examples for java.net HttpURLConnection getHeaderFields

Introduction

In this page you can find the example usage for java.net HttpURLConnection getHeaderFields.

Prototype

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

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

From source file:org.runnerup.export.GarminUploader.java

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;/*from  ww  w .  j  av  a 2s.co m*/
    s.authMethod = Uploader.AuthMethod.USER_PASS;

    FormValues fv = new FormValues();
    fv.put("service", "https://connect.garmin.com/post-auth/login");
    fv.put("clientId", "GarminConnect");
    fv.put("consumeServiceTicket", "false");

    HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv);
    addCookies(conn);
    expectResponse(conn, 200, "Connection 1: ");
    getCookies(conn);
    getFormValues(conn);
    conn.disconnect();

    // try again
    FormValues data = new FormValues();
    data.put("username", username);
    data.put("password", password);
    data.put("_eventId", "submit");
    data.put("embed", "true");
    data.put("lt", formValues.get("lt"));

    conn = post("https://sso.garmin.com/sso/login", fv);
    conn.setInstanceFollowRedirects(false);
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    postData(conn, data);
    expectResponse(conn, 200, "Connection 2: ");
    getCookies(conn);
    String html = getFormValues(conn);
    conn.disconnect();

    /* this is really horrible */
    int start = html.indexOf("?ticket=");
    if (start == -1) {
        throw new IOException("Invalid login, unable to locate ticket");
    }
    start += "?ticket=".length();
    int end = html.indexOf("'", start);
    String ticket = html.substring(start, end);
    System.err.println("ticket: " + ticket);

    // connection 3...
    fv.clear();
    fv.put("ticket", ticket);

    conn = get("https://connect.garmin.com/post-auth/login", fv);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    for (int i = 0;; i++) {
        int code = conn.getResponseCode();
        System.err.println("attempt: " + i + " => code: " + code);
        getCookies(conn);
        if (code == 200)
            break;
        if (code != 302)
            break;
        List<String> fields = conn.getHeaderFields().get("location");
        conn.disconnect();
        conn = get(fields.get(0), null);
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
    }
    conn.disconnect();

    return Status.OK; // return checkLogin();
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    // add request header
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/*from w w  w  .ja v  a  2s  .c  o  m*/

    }

    int responseCode = con.getResponseCode();
    logger.debug("Send GET http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    String result;

    try {

        result = IOUtils.toString(con.getInputStream());
        response.append(result);

    } catch (Exception e) {
        // logger.error("Error during getting input stream: ",e);
    }

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e) {
        // logger.error("Error during getting error stream: ",e);
    }

    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(responseCode);
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}

From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java

/**
 * {@inheritDoc}/*from w w  w.ja  v  a  2  s.  c om*/
 */
@Override
public WebResponse getResponse(final WebRequest webRequest) throws IOException {
    final long startTime = System.currentTimeMillis();
    final URL url = webRequest.getUrl();
    if (LOG.isTraceEnabled()) {
        LOG.trace("about to fetch URL " + url);
    }

    // hack for JS, about, and data URLs.
    final WebResponse response = produceWebResponseForGAEProcolHack(url);
    if (response != null) {
        return response;
    }

    // this is a "normal" URL
    try {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //            connection.setUseCaches(false);
        connection.setConnectTimeout(webClient_.getOptions().getTimeout());

        connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent());
        connection.setInstanceFollowRedirects(false);

        // copy the headers from WebRequestSettings
        for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) {
            connection.addRequestProperty(header.getKey(), header.getValue());
        }
        addCookies(connection);

        final HttpMethod httpMethod = webRequest.getHttpMethod();
        connection.setRequestMethod(httpMethod.name());
        if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) {
            connection.setDoOutput(true);
            final String charset = webRequest.getCharset();
            connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName());

            try (final OutputStream outputStream = connection.getOutputStream()) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                outputStream.write(query.getBytes(charset));
                if (webRequest.getRequestBody() != null) {
                    IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream);
                }
            }
        }

        final int responseCode = connection.getResponseCode();
        if (LOG.isTraceEnabled()) {
            LOG.trace("fetched URL " + url);
        }

        final List<NameValuePair> headers = new ArrayList<>();
        for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            final String headerKey = headerEntry.getKey();
            if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK")
                final StringBuilder sb = new StringBuilder();
                for (final String headerValue : headerEntry.getValue()) {
                    if (sb.length() != 0) {
                        sb.append(", ");
                    }
                    sb.append(headerValue);
                }
                headers.add(new NameValuePair(headerKey, sb.toString()));
            }
        }

        final byte[] byteArray;
        try (final InputStream is = responseCode < 400 ? connection.getInputStream()
                : connection.getErrorStream()) {
            byteArray = IOUtils.toByteArray(is);
        }

        final long duration = System.currentTimeMillis() - startTime;
        final WebResponseData responseData = new WebResponseData(byteArray, responseCode,
                connection.getResponseMessage(), headers);
        saveCookies(url.getHost(), headers);
        return new WebResponse(responseData, webRequest, duration);
    } catch (final IOException e) {
        LOG.error("Exception while tyring to fetch " + url, e);
        throw new RuntimeException(e);
    }
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/* w  w w.ja v  a  2  s.c o  m*/

    }

    con.setDoOutput(true);
    con.setRequestMethod("DELETE");
    int responseCode = con.getResponseCode();
    logger.debug("Send DELETE http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        logger.debug("response body is null");
    }

    String result;

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e2) {
        result = null;
    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(con.getResponseCode());
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTP request using {@link HttpURLConnection} in XML format.
 * //from   w  w w.j  a  v a2  s .co  m
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP 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> sendBinaryContentForXmlResponse(String endPoint, String httpMethod,
        Map<String, String> headersMap, String fileName) throws IOException, XMLStreamException {

    HttpURLConnection httpConnection = writeRequest(endPoint, httpMethod, RestResponse.XML_TYPE, headersMap,
            fileName, true);

    String responseString = readResponse(httpConnection);

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

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

    return restResponse;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTP request using {@link HttpURLConnection} in JSON format.
 * /*from  ww  w . j  a  va 2  s . c  o  m*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP 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 JSONException
 * @throws IOException
 */
protected RestResponse<JSONObject> sendBinaryContentForJsonResponse(String endPoint, String httpMethod,
        Map<String, String> headersMap, String fileName) throws IOException, JSONException {

    HttpURLConnection httpConnection = writeRequest(endPoint, httpMethod, RestResponse.JSON_TYPE, headersMap,
            fileName, true);

    String responseString = readResponse(httpConnection);

    RestResponse<JSONObject> restResponse = new RestResponse<JSONObject>();
    restResponse.setHttpStatusCode(httpConnection.getResponseCode());
    restResponse.setHeadersMap(httpConnection.getHeaderFields());

    if (responseString != null) {
        JSONObject jsonObject = null;
        if (isValidJSON(responseString)) {
            jsonObject = new JSONObject(responseString);
        } else {
            jsonObject = new JSONObject();
            jsonObject.put("output", responseString);
        }

        restResponse.setBody(jsonObject);
    }

    return restResponse;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTP request using {@link HttpURLConnection} in XML format.
 * //from w w w.  j ava 2s .  c o m
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return RestResponse
 * @throws IOException
 * @throws XMLStreamException
 */
protected RestResponse<OMElement> sendXmlRestRequest(String endPoint, String httpMethod,
        Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap)
        throws IOException, XMLStreamException {

    HttpURLConnection httpConnection = writeRequest(endPoint, httpMethod, RestResponse.XML_TYPE, headersMap,
            requestFileName, parametersMap);

    String responseString = readResponse(httpConnection);

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

    if (responseString != null) {

        if (!isValidXML(responseString)) {
            responseString = "<output>" + responseString + "</output>";
        }

        restResponse.setBody(AXIOMUtil.stringToOM(responseString));
    }

    return restResponse;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTP request using {@link HttpURLConnection} in JSON format.
 * /*from  w  w w.ja v  a 2 s  . co  m*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return RestResponse object.
 * @throws JSONException
 * @throws IOException
 */
protected RestResponse<JSONObject> sendJsonRestRequest(String endPoint, String httpMethod,
        Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap)
        throws IOException, JSONException {

    HttpURLConnection httpConnection = writeRequest(endPoint, httpMethod, RestResponse.JSON_TYPE, headersMap,
            requestFileName, parametersMap);

    String responseString = readResponse(httpConnection);

    RestResponse<JSONObject> restResponse = new RestResponse<JSONObject>();
    restResponse.setHttpStatusCode(httpConnection.getResponseCode());
    restResponse.setHeadersMap(httpConnection.getHeaderFields());

    if (responseString != null) {
        JSONObject jsonObject = null;
        if (isValidJSON(responseString)) {
            jsonObject = new JSONObject(responseString);
        } else {
            jsonObject = new JSONObject();
            jsonObject.put("output", responseString);
        }

        restResponse.setBody(jsonObject);
    }

    return restResponse;
}

From source file:info.aamulumi.sharedshopping.network.RequestSender.java

/**
 * Send HTTP Request with params (x-url-encoded)
 *
 * @param requestURL     - URL of the request
 * @param method         - HTTP method (GET, POST, PUT, DELETE, ...)
 * @param urlParameters  - parameters send in URL
 * @param bodyParameters - parameters send in body (encoded)
 * @return JSONObject returned by the server
 *//*from w  w w . j a  v a 2 s .c o  m*/
public JSONObject makeHttpRequest(String requestURL, String method, HashMap<String, String> urlParameters,
        HashMap<String, String> bodyParameters) {
    HttpURLConnection connection = null;
    URL url;
    JSONObject jObj = null;

    try {
        // Check if we must add parameters in URL
        if (urlParameters != null) {
            String stringUrlParams = getFormattedParameters(urlParameters);
            url = new URL(requestURL + "?" + stringUrlParams);
        } else
            url = new URL(requestURL);

        // Create connection
        connection = (HttpURLConnection) url.openConnection();

        // Add cookies to request
        if (mCookieManager.getCookieStore().getCookies().size() > 0)
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", mCookieManager.getCookieStore().getCookies()));

        // Set request parameters
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setDoInput(true);

        // Check if we must add parameters in body
        if (bodyParameters != null) {
            // Create a string with parameters
            String stringBodyParameters = getFormattedParameters(bodyParameters);

            // Set output request parameters
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(stringBodyParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "fr-FR");

            // Send body's request
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(stringBodyParameters);

            writer.flush();
            writer.close();
            os.close();
        }

        // Get response code
        int responseCode = connection.getResponseCode();

        // If response is 200 (OK)
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            // Keep new cookies in the manager
            List<String> cookiesHeader = connection.getHeaderFields().get(COOKIES_HEADER);
            if (cookiesHeader != null) {
                for (String cookie : cookiesHeader)
                    mCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }

            // Read the response
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }

            // Parse the response to a JSON Object
            try {
                jObj = new JSONObject(sb.toString());
            } catch (JSONException e) {
                Log.d("JSON Parser", "Error parsing data " + e.toString());
                Log.d("JSON Parser", "Setting value of jObj to null");
                jObj = null;
            }
        } else {
            Log.w("HttpUrlConnection", "Error : server sent code : " + responseCode);
        }
    } catch (MalformedURLException e) {
        Log.e("Network", "Error in URL");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close connection
        if (connection != null)
            connection.disconnect();
    }

    return jObj;
}