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:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from   ww w . j  av  a2 s .  c  om*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

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

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}

From source file:org.jclouds.http.internal.JavaUrlHttpCommandExecutorService.java

@Override
protected HttpResponse invoke(HttpURLConnection connection) throws IOException {
    HttpResponse response = new HttpResponse();
    InputStream in;/*from  w w  w . j a  va2 s .c  o  m*/
    try {
        in = connection.getInputStream();
    } catch (IOException e) {
        in = connection.getErrorStream();
    }
    if (in != null) {
        response.setContent(in);
    }
    for (String header : connection.getHeaderFields().keySet()) {
        response.getHeaders().putAll(header, connection.getHeaderFields().get(header));
    }
    response.setStatusCode(connection.getResponseCode());
    response.setMessage(connection.getResponseMessage());
    return response;
}

From source file:test.ShopThreadSrc.java

private String addJSDynamicParams() throws Exception {
    HttpURLConnection conn = getHttpGetConn(this.jsshopurl);
    Parser parser = new Parser(conn);
    parser.setEncoding("UTF-8");
    NodeList list = parser.parse(null);
    Map<String, List<String>> header = conn.getHeaderFields();
    LogUtil.debugPrintf("conn.getHeaderFields():" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        LogUtil.infoPrintf("?----------->");
    } else {/*from w ww. j a  v a 2 s.com*/
        LogUtil.infoPrintf("??----------->");
        LogUtil.debugPrintf("cookie====" + cookie);
        setCookies(cookie);
    }

    StringBuffer dyparams = new StringBuffer(4000);
    NodeList a1ab = list
            .extractAllNodesThatMatch(new HasAttributeFilter("id", "0915324f09d34f42a6b45b9d4235a1ab"), true);
    InputTag alabinput = (InputTag) a1ab.elementAt(0);
    String value = alabinput.getAttribute("value");
    LogUtil.debugPrintf("alabinput:" + value);
    dyparams.append("0915324f09d34f42a6b45b9d4235a1ab=" + URLEncoder.encode(value, "utf-8"));
    /************************************************************/
    dyparams.append("&__EVENTTARGET=&__EVENTARGUMENT=");
    /************************************************************/
    NodeList __VIEWSTATE = list.extractAllNodesThatMatch(new HasAttributeFilter("id", "__VIEWSTATE"), true);
    InputTag stateinput = (InputTag) __VIEWSTATE.elementAt(0);
    value = stateinput.getAttribute("value");
    LogUtil.debugPrintf("stateinput:" + value);
    dyparams.append("&__VIEWSTATE=" + URLEncoder.encode(value, "utf-8"));
    /************************************************************/
    dyparams.append("&hfVipKeFuId=js-kf-576");
    dyparams.append("&header%24CommSearchBarNew5%24txtStuffCatagoryID=");
    dyparams.append(
            "&header%24CommSearchBarNew5%24txtBizTypes=&header%24CommSearchBarNew5%24txtGameID=&header%24CommSearchBarNew5%24txtGameAreas=");
    dyparams.append("&header%24CommSearchBarNew5%24txtGameServers=");
    dyparams.append("&header%24CommSearchBarNew5%24txtGameBizType=");
    dyparams.append("&header%24CommSearchBarNew5%24txtSearchKeyWord=");
    dyparams.append(
            "&header%24CommSearchBarNew5%24txtKeyword=%C7%EB%CA%E4%C8%EB%C8%CE%D2%E2%B9%D8%BC%FC%D7%D6");
    dyparams.append("&ddrQuantity=1");
    dyparams.append("&txtReOldRole=");
    dyparams.append("&txtReceivingRole=121212");
    dyparams.append("&txtSureReceivingRole=121212");
    dyparams.append("&txtReOldGameId=");
    dyparams.append("&txtRoleHierarchy=12");
    dyparams.append("&bzon=rdbtnOffPostSaleIndemnity");
    dyparams.append("&txtPhone=158****3613");
    dyparams.append("&txtQq=650000000");
    dyparams.append("&hiddenBtnSureOk=");
    dyparams.append("&HiddenField3=");
    dyparams.append("&hdfHistoryType=");
    dyparams.append("&hd_OriginalUnitQuantityMoney=");
    dyparams.append("&hd_OriginalUnitPirce=12.00");
    dyparams.append("&hd_gameRoleValue=121212");
    /************************************************************/
    return dyparams.toString();
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

private void readResponse(HttpURLConnection http, AdaptrisMessage reply) throws IOException, CoreException {
    int responseCode = http.getResponseCode();
    logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    log.trace("Content-Length is " + http.getContentLength());

    if (responseCode < 200 || responseCode > 299) {
        if (ignoreServerResponseCode()) {
            log.trace("Ignoring HTTP Reponse code {}", responseCode);
            processErrorReply(http, reply);
            return;
        } else {/*from   w  w w  .  ja va  2 s.c o  m*/
            throw new ProduceException("Failed to send payload, got " + responseCode);
        }
    }
    if (getEncoder() != null) {
        copy(getEncoder().readMessage(http), reply);
    } else {
        processReply(http, reply);
    }
}

From source file:com.shinymayhem.radiopresets.ServiceAudioFormat.java

private Map<String, List<String>> getInputStream(String url) throws IOException, StreamHttpException {
    /*//from  w w w . ja  va2 s.co  m
    URL streamUrl = new URL(url);
    StreamURLConnection con;
    con = (StreamURLConnection)streamUrl.openConnection();
    con.setRequestProperty("Connection", "close");
    con.connect();
    int responseCode = con.getResponseCode(); 
    if (responseCode < 200 || responseCode >= 300)
    {
    this.handleHttpError(con);
    }*/
    URL streamUrl = new URL(url);
    HttpURLConnection con;
    con = (HttpURLConnection) streamUrl.openConnection();
    con.setRequestProperty("Connection", "close");
    con.connect();
    Map<String, List<String>> headers = con.getHeaderFields();
    String statusLine = headers.get(null).get(0); //con.getHeaderField(0);
    //String statusLine2 = con.getHeaderField(0);
    String message = statusLine;
    int responseCode = -1;
    if (statusLine.startsWith("HTTP/1.") || statusLine.startsWith("ICY")) {
        int codePos = statusLine.indexOf(' ');
        if (codePos > 0) {

            int phrasePos = statusLine.indexOf(' ', codePos + 1);
            if (phrasePos > 0 && phrasePos < statusLine.length()) {
                message = statusLine.substring(phrasePos + 1);
            }

            if (phrasePos < 0)
                phrasePos = statusLine.length();

            try {
                responseCode = Integer.parseInt(statusLine.substring(codePos + 1, phrasePos));
            } catch (NumberFormatException e) {
            }
        }
    }

    this.handleHttpResponse(responseCode, message);
    mStream = con.getInputStream();
    return headers;
}

From source file:com.gliffy.restunit.http.JavaHttp.java

private HttpResponse createResponse(HttpURLConnection connection) throws IOException {
    HttpResponse response = new HttpResponse();
    response.setStatusCode(connection.getResponseCode());
    if (response.getStatusCode() == HttpURLConnection.HTTP_OK) {
        response.setBody(readBody(connection));
    } else {//from ww w. j av a  2s.  c  om
        itsLogger.debug(
                "Got " + response.getStatusCode() + " and java.net will barf if we try to read the body");
    }
    for (String header : connection.getHeaderFields().keySet()) {
        response.getHeaders().put(header, joinHeaderValues(connection.getHeaderFields().get(header)));
    }
    return response;
}

From source file:uk.ac.gate.cloud.client.RestClient.java

private void storeHeaders(HttpURLConnection connection) {
    lastResponseHeaders.set(connection.getHeaderFields());
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private void handleResponse(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, InterlokException {
    int responseCode = http.getResponseCode();
    logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    log.trace("Content-Length is " + http.getContentLength());

    if (responseCode < 200 || responseCode > 299) {
        if (ignoreServerResponseCode()) {
            log.trace("Ignoring HTTP Reponse code {}", responseCode);
            responseBody().insert(new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)),
                    reply);//from w  w w. j  ava 2  s .co  m
        } else {
            fail(responseCode, new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)));
        }
    } else {
        if (getEncoder() != null) {
            AdaptrisMessage decodedReply = getEncoder().readMessage(http);
            AdaptrisMessageImp.copyPayload(decodedReply, reply);
            reply.getObjectHeaders().putAll(decodedReply.getObjectHeaders());
            reply.setMetadata(decodedReply.getMetadata());
        } else {
            responseBody().insert(new InputStreamWithEncoding(http.getInputStream(), getContentEncoding(http)),
                    reply);
        }
    }
    getResponseHeaderHandler().handle(http, reply);
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
    reply.addObjectHeader(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE, Integer.valueOf(http.getResponseCode()));
}

From source file:io.apiman.manager.ui.server.servlets.ApiManagerProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   www .  j ava2 s .  c o m
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StringBuilder url = new StringBuilder();

    String endpoint = getConfig().getManagementApiEndpoint();
    if (endpoint == null) {
        endpoint = getDefaultEndpoint(req);
    }

    url.append(endpoint);
    if (!url.toString().endsWith("/")) { //$NON-NLS-1$
        url.append('/');
    }
    String pathInfo = req.getPathInfo();
    if (pathInfo != null && pathInfo.startsWith("/")) { //$NON-NLS-1$
        url.append(pathInfo.substring(1));
    } else {
        url.append(pathInfo);
    }

    String authHeaderValue = null;
    ApiAuthType authType = getConfig().getManagementApiAuthType();
    switch (authType) {
    case basic: {
        String username = getConfig().getManagementApiAuthUsername();
        String password = getConfig().getManagementApiAuthPassword();
        String encoded = base64Encode(username + ":" + password); //$NON-NLS-1$
        authHeaderValue = "Basic " + encoded; //$NON-NLS-1$
        break;
    }
    case authToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "AUTH-TOKEN " + token; //$NON-NLS-1$
        break;
    }
    case bearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "Bearer " + token; //$NON-NLS-1$
        break;
    }
    case samlBearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        // TODO base64 decode the token, then re-encode it with "SAML-BEARER-TOKEN:"
        authHeaderValue = "Basic SAML-BEARER-TOKEN:" + token; //$NON-NLS-1$
        break;
    }
    }

    URL remoteUrl = new URL(url.toString());
    HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection();
    InputStream remoteIS = null;
    OutputStream responseOS = null;
    try {
        if (authHeaderValue != null) {
            remoteConn.setRequestProperty("Authorization", authHeaderValue); //$NON-NLS-1$
        }
        remoteConn.connect();
        Map<String, List<String>> headerFields = remoteConn.getHeaderFields();
        for (String headerName : headerFields.keySet()) {
            if (headerName == null) {
                continue;
            }
            if (EXCLUDE_HEADERS.contains(headerName)) {
                continue;
            }
            String headerValue = remoteConn.getHeaderField(headerName);
            resp.setHeader(headerName, headerValue);
            if (url.toString().contains("apiregistry")) { //$NON-NLS-1$
                String type = "json"; //$NON-NLS-1$
                if (url.toString().endsWith("xml")) { //$NON-NLS-1$
                    type = "xml"; //$NON-NLS-1$
                }
                resp.setHeader("Content-Disposition", "attachment; filename=api-registry." + type); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$
        remoteIS = remoteConn.getInputStream();
        responseOS = resp.getOutputStream();
        IOUtils.copy(remoteIS, responseOS);
        resp.flushBuffer();
    } catch (Exception e) {
        resp.sendError(500, e.getMessage());
    } finally {
        IOUtils.closeQuietly(responseOS);
        IOUtils.closeQuietly(remoteIS);
    }
}

From source file:test.ShopThreadSrc.java

private String addPTDynamicParams() throws Exception {
    HttpURLConnection conn = getHttpGetConn(this.ptshopurl);
    conn.setRequestProperty("Host", "danbao.5173.com");
    Parser parser = new Parser(conn);
    parser.setEncoding("UTF-8");
    NodeList list = parser.parse(null);
    Map<String, List<String>> header = conn.getHeaderFields();
    LogUtil.debugPrintf("conn.getHeaderFields():" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        LogUtil.infoPrintf("?----------->");
    } else {/*from  w  ww  .  j a va 2 s .  c  o m*/
        LogUtil.infoPrintf("??----------->");
        LogUtil.debugPrintf("cookie====" + cookie);
        setCookies(cookie);
    }

    StringBuffer dyparams = new StringBuffer(4000);
    NodeList a1ab = list
            .extractAllNodesThatMatch(new HasAttributeFilter("id", "0915324f09d34f42a6b45b9d4235a1ab"), true);
    InputTag alabinput = (InputTag) a1ab.elementAt(0);
    String value = alabinput.getAttribute("value");
    LogUtil.debugPrintf("alabinput:" + value);
    dyparams.append("0915324f09d34f42a6b45b9d4235a1ab=" + URLEncoder.encode(value, "utf-8"));
    /************************************************************/
    dyparams.append("&__EVENTTARGET=&__EVENTARGUMENT=");
    /************************************************************/
    NodeList __VIEWSTATE = list.extractAllNodesThatMatch(new HasAttributeFilter("id", "__VIEWSTATE"), true);
    InputTag stateinput = (InputTag) __VIEWSTATE.elementAt(0);
    value = stateinput.getAttribute("value");
    LogUtil.debugPrintf("stateinput:" + value);
    dyparams.append("&__VIEWSTATE=" + URLEncoder.encode(value, "utf-8"));
    /************************************************************/
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtStuffCatagoryID=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtBizTypes=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtGameID=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtGameAreas=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtGameServers=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtGameBizType=");
    dyparams.append("&SearchHeadNew1%24CommSearchBarNew5%24txtSearchKeyWord=");
    dyparams.append(
            "&SearchHeadNew1%24CommSearchBarNew5%24txtKeyword=%C7%EB%CA%E4%C8%EB%C8%CE%D2%E2%B9%D8%BC%FC%D7%D6");
    dyparams.append("&PurchaseOrderNew1%24hdGameMoney=");
    dyparams.append("&PurchaseOrderNew1%24hdPrice=200.0000");
    dyparams.append("&PurchaseOrderNew1%24hdDefFee=0.00");
    dyparams.append("&PurchaseOrderNew1%24QuantityInfo1%24ddlQuantity=1");
    dyparams.append("&PurchaseOrderNew1%24BuyerGameRoleInfo1%24txtGameRole=2000");
    dyparams.append("&PurchaseOrderNew1%24BuyerGameRoleInfo1%24txtGameRoleValidate=2000");
    dyparams.append("&PurchaseOrderNew1%24txtRoleGrade=100");
    dyparams.append("&PurchaseOrderNew1%24hide_VipKefuId=db-kf-5637");
    dyparams.append("&PurchaseOrderNew1%24rdPostSaleGroup=rdNoPostSale");
    dyparams.append("&PurchaseOrderNew1%24txtBuyerTel=158****3613");
    dyparams.append("&PurchaseOrderNew1%24hdLastBuyerTel=158****3613");
    dyparams.append("&PurchaseOrderNew1%24txtBuyerQQ=65000000");
    dyparams.append("&PurchaseOrderNew1%24btnCreateOrder=%CC%E1%BD%BB%B2%E9%D1%AF");
    dyparams.append("&PurchaseOrderNew1%24cbAgreeLicense=on");
    /************************************************************/
    return dyparams.toString();
}