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.dao.ShopThread.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.debugPrintf("?----------->");
    } else {/* w ww  . j  a  v  a 2 s. co m*/
        LogUtil.debugPrintf("??----------->");
        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"));

    NodeList scrilist = list.extractAllNodesThatMatch(new HasAttributeFilter("type", "text/javascript"), true);
    ScriptTag jstag = null;
    String hfVipKeFuId = "";
    for (int i = 0; i < scrilist.size(); i++) {
        jstag = (ScriptTag) scrilist.elementAt(i);
        if (jstag == null)
            continue;
        String scrstr = jstag.toPlainTextString();
        if (scrstr.contains("vipKefuJsonDatas")) {
            int beginindex = scrstr.indexOf("{");
            int endindex = scrstr.indexOf("};");
            scrstr = scrstr.substring(beginindex, endindex + 1);
            LogUtil.debugPrintf("jstag==" + scrstr);
            JSONObject jsonobj = new JSONObject(scrstr);
            JSONArray customers = (JSONArray) jsonobj.get(this.getParams().getString("customer"));// ?Star1Star5
            hfVipKeFuId = (String) ((JSONObject) (customers.get(0))).get("Id");
            LogUtil.debugPrintf("hfVipKeFuId==" + hfVipKeFuId);
        }
    }

    /************************************************************/
    dyparams.append("&hfVipKeFuId=" + hfVipKeFuId);
    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=" + this.getParams().getString("txtGameRole"));
    dyparams.append("&txtSureReceivingRole=" + this.getParams().getString("txtGameRole"));
    dyparams.append("&txtReOldGameId=");
    dyparams.append("&txtRoleHierarchy=" + this.getParams().getString("rolelevel"));
    dyparams.append("&bzon=rdbtnOffPostSaleIndemnity");
    dyparams.append("&txtPhone=" + this.getParams().getString("txtBuyerTel"));
    dyparams.append("&txtQq=" + this.getParams().getString("txtBuyerQQ"));
    dyparams.append("&hiddenBtnSureOk=");
    dyparams.append("&HiddenField3=");
    dyparams.append("&hdfHistoryType=");
    dyparams.append("&hd_OriginalUnitQuantityMoney=");
    dyparams.append("&hd_OriginalUnitPirce=" + this.getParams().getString("price"));
    dyparams.append("&hd_gameRoleValue=" + this.getParams().getString("txtGameRole"));
    /************************************************************/
    return dyparams.toString();
}

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

private void processReply(HttpURLConnection http, AdaptrisMessage reply) throws IOException, CoreException {
    InputStream in = null;/*  w w w  .  j  a v a2 s  . c om*/
    OutputStream out = null;
    try {
        if (http.getContentLength() < TWO_MEG) {
            in = http.getInputStream();
            out = reply.getOutputStream();
        } else {
            out = new BufferedOutputStream(reply.getOutputStream(), FOUR_MEG);
            in = new BufferedInputStream(http.getInputStream(), FOUR_MEG);
        }
        StreamUtil.copyStream(in, out);
        if (httpHeadersAsMetadata()) {
            addReplyMetadata(http.getHeaderFields(), reply);
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
}

From source file:com.dao.ShopThread.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.debugPrintf("???----------->");
    } else {//ww w. j  a v a2  s .  co m
        LogUtil.debugPrintf("????----------->");
        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"));
    NodeList scrilist = list.extractAllNodesThatMatch(new HasAttributeFilter("type", "text/javascript"), true);
    ScriptTag jstag = null;
    String hide_VipKefuId = "";
    for (int i = 0; i < scrilist.size(); i++) {
        jstag = (ScriptTag) scrilist.elementAt(i);
        if (jstag == null)
            continue;
        String scrstr = jstag.toPlainTextString();
        if (scrstr.contains("vipKefuJsonDatas")) {
            int beginindex = scrstr.indexOf("{");
            int endindex = scrstr.indexOf("};");
            scrstr = scrstr.substring(beginindex, endindex + 1);
            LogUtil.debugPrintf("jstag==" + scrstr);
            JSONObject jsonobj = new JSONObject(scrstr);
            JSONArray customers = (JSONArray) jsonobj.get(this.getParams().getString("customer"));// ?Star1Star5
            hide_VipKefuId = (String) ((JSONObject) (customers.get(0))).get("Id");
            LogUtil.debugPrintf("hide_VipKefuId==" + hide_VipKefuId);
        }
    }
    /************************************************************/
    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=" + this.getParams().getString("price"));
    dyparams.append("&PurchaseOrderNew1%24hdDefFee=0.00");
    dyparams.append("&PurchaseOrderNew1%24QuantityInfo1%24ddlQuantity=1");
    dyparams.append("&PurchaseOrderNew1%24BuyerGameRoleInfo1%24txtGameRole="
            + URLEncoder.encode(this.getParams().getString("txtGameRole"), "gb2312"));
    dyparams.append("&PurchaseOrderNew1%24BuyerGameRoleInfo1%24txtGameRoleValidate="
            + URLEncoder.encode(this.getParams().getString("txtGameRole"), "gb2312"));
    dyparams.append("&PurchaseOrderNew1%24txtRoleGrade=" + this.getParams().getString("rolelevel"));
    dyparams.append("&PurchaseOrderNew1%24hide_VipKefuId=" + hide_VipKefuId);
    dyparams.append("&PurchaseOrderNew1%24rdPostSaleGroup=rdNoPostSale");
    dyparams.append("&PurchaseOrderNew1%24txtBuyerTel=" + this.getParams().getString("txtBuyerTel"));
    dyparams.append("&PurchaseOrderNew1%24hdLastBuyerTel=" + this.getParams().getString("txtBuyerTel"));
    dyparams.append("&PurchaseOrderNew1%24txtBuyerQQ=" + this.getParams().getString("txtBuyerQQ"));
    dyparams.append("&PurchaseOrderNew1%24btnCreateOrder=%CC%E1%BD%BB%B2%E9%D1%AF");
    dyparams.append("&PurchaseOrderNew1%24cbAgreeLicense=on");
    /************************************************************/
    return dyparams.toString();
}

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

private void processErrorReply(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, CoreException {
    InputStream error = null;//from w ww .  ja v  a  2 s  . c o m
    OutputStream out = null;
    try {
        if (http.getContentLength() < TWO_MEG) {
            error = http.getErrorStream();
            out = reply.getOutputStream();
        } else {
            out = new BufferedOutputStream(reply.getOutputStream(), FOUR_MEG);
            error = new BufferedInputStream(http.getErrorStream(), FOUR_MEG);
        }
        StreamUtil.copyStream(error, out);
        if (httpHeadersAsMetadata()) {
            addReplyMetadata(http.getHeaderFields(), reply);
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(out);
    }
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
}

From source file:test.ShopThreadSrc.java

private boolean doJSShop() throws Exception {
    LogUtil.infoPrintf("?----------->");
    //loadCookie();
    boolean result = true;
    String postParams = addJSDynamicParams();
    HttpURLConnection loginConn = getHttpPostConn(this.jsshopurl);
    loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
    LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties());
    DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
    wr.writeBytes(postParams);//w ww. j  a va2  s  . co m
    wr.flush();
    wr.close();
    int responseCode = loginConn.getResponseCode();
    LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.jsshopurl);
    LogUtil.debugPrintf("Post parameters : " + postParams);
    LogUtil.debugPrintf("Response Code : " + responseCode);
    Map<String, List<String>> header = loginConn.getHeaderFields();
    LogUtil.debugPrintf("??HEADER===" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        result = false;
        LogUtil.infoPrintf("?----------->");
    } else {
        LogUtil.infoPrintf("??----------->");
        LogUtil.debugPrintf("cookie====" + cookie);
        setCookies(cookie);
    }
    LogUtil.infoPrintf("??----------->");
    //System.out.println(list.toHtml());
    return result;
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP get for a given URL/*from  ww w. j av  a2  s .c  o m*/
 * 
 * @param url
 *            is the URL to get
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doGet(URL url) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        Map<String, List<String>> responseHeaderFields = conn.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line;
            do {
                line = buff.readLine();
                System.out.println(line + "\n");
            } while (line != null);
        }
        return responseHeaderFields;
    } catch (IOException e) {
        fail = e.getLocalizedMessage();
        return null;
    }
}

From source file:com.github.thesmartenergy.sparql.generate.api.Fetch.java

@GET
public Response doFetch(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("http://localhost:8080/sparql-generate/example/example1") @QueryParam("uri") String uri,
        @DefaultValue("*/*") @QueryParam("useaccept") String useaccept,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    HttpURLConnection con;
    String message = null;/*from w ww.j  a  v  a 2s.c o m*/
    URL obj;
    try {
        obj = new URL(uri);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", useaccept);
        con.setInstanceFollowRedirects(true);
        System.out.println("GET to " + uri + " returned " + con.getResponseCode());
        InputStream in = con.getInputStream();
        message = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access message at URI <" + uri + ">: " + e.getMessage()).build();
    }

    Map<String, List<String>> headers = con.getHeaderFields();
    if (!headers.containsKey("Link")) {
        return Response.status(Response.Status.BAD_REQUEST).entity(
                "Error while processing message at URI <" + uri + ">: there should be a Link header field")
                .build();
    }
    String var = null;
    URL qobj = null;
    for (String linkstr : headers.get("Link")) {
        Link link = Link.valueOf(linkstr);
        if (link.getRels().contains("https://w3id.org/sparql-generate/voc#spargl-query")
                || link.getRels().contains("spargl-query")) {
            Map<String, String> params = link.getParams();
            // check the context
            // check syntax for variable ?
            var = params.getOrDefault("var", "message");
            // ok for relative and absolute URIs ?
            try {
                qobj = obj.toURI().resolve(link.getUri()).toURL();
                System.out.println("found link " + qobj + " and var " + var);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            break;
        }
        // what if multiple suitable links ? 
    }

    if (var == null || qobj == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Error while processing message at URI <"
                + uri
                + ">: did not find a suitable link with relation spargl-query, or https://w3id.org/sparql-generate/voc#spargl-query")
                .build();
    }

    HttpURLConnection qcon;
    String query;
    try {
        qcon = (HttpURLConnection) qobj.openConnection();
        qcon.setRequestMethod("GET");
        qcon.setRequestProperty("Accept", "application/sparql-generate");
        qcon.setInstanceFollowRedirects(true);
        System.out.println("GET to " + qobj + " returned " + qcon.getResponseCode());
        InputStream in = qcon.getInputStream();
        query = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access query at URI <" + qobj + ">: " + e.getMessage()).build();
    }

    System.out.println("got query " + query);

    // parse the SPARQL-Generate query and create plan
    PlanFactory factory = new PlanFactory();

    Syntax syntax = SPARQLGenerate.SYNTAX;
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax);
    if (q.getBaseURI() == null) {
        q.setBaseURI("http://example.org/");
    }
    RootPlan plan = factory.create(q);

    // create the initial model
    Model model = ModelFactory.createDefaultModel();

    // if content encoding is not text-based, then use base64 encoding
    // use con.getContentEncoding() for this

    String dturi = "http://www.w3.org/2001/XMLSchema#string";
    String ct = con.getContentType();
    if (ct != null) {
        dturi = "urn:iana:mime:" + ct;
    }

    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(dturi);
    Node arqLiteral = NodeFactory.createLiteral(message, dt);
    RDFNode jenaLiteral = model.asRDFNode(arqLiteral);
    initialBinding.add(var, jenaLiteral);

    // execute the plan
    plan.exec(initialBinding, model);

    System.out.println(accept);
    if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) {
        List<Variant> vs = Variant
                .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build();
        Variant v = r.selectVariant(vs);
        accept = v.getMediaType().toString();
    }

    System.out.println(accept);
    StringWriter sw = new StringWriter();
    Response.ResponseBuilder res;
    if (accept.equals("application/rdf+xml")) {
        model.write(sw, "RDF/XML", "http://example.org/");
        res = Response.ok(sw.toString(), "application/rdf+xml");
        res.header("Content-Disposition", "filename= message.rdf;");
        return res.build();
    } else {
        model.write(sw, "TTL", "http://example.org/");
        res = Response.ok(sw.toString(), "text/turtle");
        res.header("Content-Disposition", "filename= message.ttl;");
        return res.build();
    }
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProvider.java

private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException {

    int statusCode = urlConnection.getResponseCode();
    HeaderAndBody result;//from  w ww  . j  a v a  2 s.c  o m
    Map<String, List<String>> headers;
    byte[] responseData;

    switch (statusCode) {
    case HttpStatus.SC_OK:
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        responseData = readBytes(in);

        break;

    case HttpStatus.SC_NO_CONTENT:
        responseData = new byte[0];

        break;

    default:
        InputStream err = new BufferedInputStream(urlConnection.getErrorStream());

        byte[] errData = readBytes(err);

        Map<String, String> errorHeaders = Maps.transformValues(urlConnection.getHeaderFields(),
                new Function<List<String>, String>() {
                    @Override
                    public String apply(List<String> input) {
                        return TextUtils.join(",", input);
                    }
                });

        throw new HttpException(errData, statusCode, errorHeaders);

    }

    headers = urlConnection.getHeaderFields();
    result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size()));

    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        result.setHeader(header.getKey(), TextUtils.join(",", header.getValue()));
    }

    return result;

}

From source file:org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTransport.java

public static ServiceResult doPOST_PUT(String urlString, String content, String contentRaw, String boundary,
        String method, String contentType, String authForTest, String fromTestID) throws Exception {
    ServiceResult result = new ServiceResult();
    result.method = method;//from w w  w  . java  2s  .co  m
    String deleteURL = "";
    String location = "";
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();

        if (MULTIPART_MIXED.equalsIgnoreCase(contentType)) {
            conn.setRequestProperty("Accept", "multipart/mixed");
            conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary);
        } else {
            conn.setRequestProperty("Accept", "application/xml");
            conn.setRequestProperty("content-type", contentType);
        }
        conn.setRequestProperty("Authorization", "Basic " + authForTest); //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0"
        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method); // "POST" or "PUT"
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(content);
        wr.flush();

        try {
            result.requestPayload = content;
            result.requestPayloadsRaw = contentRaw;
            result.responseCode = conn.getResponseCode();
            //System.out.println("responseCode: "+result.responseCode);
            if (400 <= result.responseCode && result.responseCode <= 499) {
                return result;
            }
            readStream(conn, result);
        } catch (Throwable t) {
            //System.err.println("ERROR getting content from response: "+t);
            result.error = t.toString();
        }
        wr.close();

        Map<String, List<String>> headers = conn.getHeaderFields();
        List<String> locations = headers.get("Location");
        if (locations != null) {
            String locationZero = locations.get(0);
            if (locationZero != null) {
                String[] segments = locationZero.split("/");
                location = segments[segments.length - 1];
                deleteURL = Tools.glue(urlString, "/", location);
            }
        }
        result.location = location;
        result.deleteURL = deleteURL;
        result.CSID = location;
    } catch (Throwable t2) {
        result.error = "ERROR in XmlReplayTransport: " + t2;
    }
    return result;
}

From source file:org.inaetics.pubsub.demo.config.EtcdWrapper.java

public JsonNode createDirectory(String key) throws UnsupportedEncodingException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url + key).openConnection();
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    String query = String.format("dir=%s", URLEncoder.encode("true", charset));

    try (OutputStream output = connection.getOutputStream()) {
        output.write(query.getBytes(charset));
    }/*from  w  w  w  .j a  v a  2s  .  c  o  m*/

    InputStream response = connection.getInputStream();
    JsonNode result = new ObjectMapper().readTree(response);
    response.close();

    AddEtcdIndex(result, Long.parseLong(connection.getHeaderFields().get("X-Etcd-Index").get(0)));
    return result;
}