Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

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

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:io.mindmaps.loader.DistributedLoader.java

private String executePost(HttpURLConnection connection, String body) {

    try {/*from   w  w  w.j a  v a 2 s  .co  m*/
        // create post
        connection.setRequestMethod(RESTUtil.HttpConn.POST_METHOD);
        connection.addRequestProperty(RESTUtil.HttpConn.CONTENT_TYPE, RESTUtil.HttpConn.APPLICATION_POST_TYPE);

        // add body and execute
        connection.setRequestProperty(RESTUtil.HttpConn.CONTENT_LENGTH, Integer.toString(body.length()));
        connection.getOutputStream().write(body.getBytes(RESTUtil.HttpConn.UTF8));

        // get response
        return connection.getResponseMessage();
    } catch (HTTPException e) {
        LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(),
                e.getStatusCode(), getResponseMessage(connection), body));
    } catch (IOException e) {
        LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString()));
    }

    return null;
}

From source file:org.callimachusproject.test.WebResource.java

public byte[] post(String type, byte[] body, String accept) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept", accept);
    con.setRequestProperty("Accept-Encoding", "gzip");
    con.setRequestProperty("Content-Type", type);
    con.setDoOutput(true);/*from   w  w  w.j a  v  a 2  s .  com*/
    OutputStream req = con.getOutputStream();
    try {
        req.write(body);
    } finally {
        req.close();
    }
    Assert.assertEquals(con.getResponseMessage(), 200, con.getResponseCode());
    InputStream in = con.getInputStream();
    try {
        if ("gzip".equals(con.getHeaderField("Content-Encoding"))) {
            in = new GZIPInputStream(in);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ChannelUtil.transfer(in, out);
        return out.toByteArray();
    } finally {
        in.close();
    }
}

From source file:it.infn.ct.jsaga.adaptor.tosca.ToscaAdaptorCommon.java

protected String getToscaDeployment(String toscaUUID) {
    StringBuilder deployment = new StringBuilder();
    HttpURLConnection conn;
    try {/*from   w ww . jav  a  2 s .c  om*/
        log.debug("endpoint: '" + endpoint + "'");
        URL deploymentEndpoint = new URL(endpoint.toString() + "/" + toscaUUID);
        log.debug("deploymentEndpoint: '" + deploymentEndpoint + "'");
        conn = (HttpURLConnection) deploymentEndpoint.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        log.debug("Orchestrator status code: " + conn.getResponseCode());
        log.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String ln;
            while ((ln = br.readLine()) != null) {
                deployment.append(ln);
            }
            log.debug("Orchestrator result: " + deployment);
        }
    } catch (IOException ex) {
        log.error("Connection error with the service at " + endpoint.toString());
        log.error(ex);
    }
    return deployment.toString();
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

private void closeConnection(HttpURLConnection connection) throws IOException {
    connection.getOutputStream().close();
    connection.disconnect();//from w ww  .  ja v  a2  s  .  co  m
    // we have to call this, otherwise out HTTP data does not get send, even though close()/disconnect was called
    if (connection.getResponseCode() != 200) {
        LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(),
                connection.getResponseMessage());
    }
}

From source file:org.callimachusproject.test.WebResource.java

public WebResource create(Map<String, String> headers, String type, byte[] body) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("POST");
    for (Map.Entry<String, String> e : headers.entrySet()) {
        con.setRequestProperty(e.getKey(), e.getValue());
    }//w  w w  . ja va  2  s . co  m
    con.setRequestProperty("Content-Type", type);
    con.setDoOutput(true);
    OutputStream out = con.getOutputStream();
    try {
        out.write(body);
    } finally {
        out.close();
    }
    Assert.assertEquals(con.getResponseMessage(), 201, con.getResponseCode());
    String header = con.getHeaderField("Location");
    Assert.assertNotNull(header);
    return ref(header);
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

private StructureType retrieve2(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").info("ILORestServiceRegistry: retrieve " + urlString + "&" + options);
    String s = options;/*from  w ww. j  a  va  2  s. c om*/
    if (urlString.indexOf("?") == -1) {
        s = "?" + s;
    } else {
        s = "&" + s;
    }
    URL url = new URL(urlString + s);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    InputStream in = conn.getInputStream();
    //FileOutputStream temp = new FileOutputStream("temp.xml");
    //org.apache.commons.io.IOUtils.copy(in, temp);
    //temp.close();
    //in.close();
    //in = new FileInputStream("temp.xml");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ie) {
    }
    System.out.println("Parsing!");
    ParseParams params = new ParseParams();
    params.setRegistry(this);
    StructureType st = SdmxIO.parseStructure(params, in);
    if (st == null) {
        System.out.println("St is null!");
    }
    return st;
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private void readErrorFromConnection(HttpURLConnection c, String logPrefix, String message) throws IOException {
    int rc = c.getResponseCode();
    String msg = c.getResponseMessage();
    log.error(logPrefix + ": " + rc + " " + msg);
    InputStream errors = c.getErrorStream();
    if (errors != null) {
        for (String line : readLines(errors))
            log.error(logPrefix + ": " + line);
        errors.close();/*from w w w  . j a  v a2  s .  c  om*/
    }
    throw new InternalServerErrorException(format(message, rc, msg));
}

From source file:export.GarminUploader.java

private Status checkLogin() throws MalformedURLException, IOException, JSONException {
    HttpURLConnection conn = (HttpURLConnection) new URL(CHECK_URL).openConnection();
    addCookies(conn);//from  w ww . j a  v a 2  s .com
    {
        conn.connect();
        getCookies(conn);
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JSONObject obj = parse(in);
        conn.disconnect();
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        // Returns username(which is actually Displayname from profile) if
        // logged in
        if (obj.optString("username", "").length() > 0) {
            isConnected = true;
            return Uploader.Status.OK;
        } else {
            System.err.println("GarminUploader::connect() missing username, obj: " + obj.toString() + ", code: "
                    + responseCode + ", msg: " + amsg);
        }
        Status s = Status.NEED_AUTH;
        s.authMethod = Uploader.AuthMethod.USER_PASS;
        return s;
    }
}

From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java

private void closeConnection(HttpURLConnection connection) throws IOException {
    connection.getOutputStream().close();
    connection.disconnect();/*w w  w  .  j a v  a2 s  . co  m*/

    // we have to call this, otherwise out HTTP data does not get send, even though close()/disconnect was called
    // Ceterum censeo HttpUrlConnection esse delendam
    if (connection.getResponseCode() != HttpStatus.OK.value()) {
        LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(),
                connection.getResponseMessage());
    }
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

private StructureType retrieve(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").info("NOMISRESTServiceRegistry: retrieve " + urlString);
    String s = options;/*from   www  .ja  v  a2  s. c om*/
    if (urlString.indexOf("?") == -1) {
        s = "?" + s + "&random=" + System.currentTimeMillis();
    } else {
        s = "&" + s + "&random=" + System.currentTimeMillis();
    }
    URL url = new URL(urlString + s);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    InputStream in = conn.getInputStream();
    if (SdmxIO.isSaveXml()) {
        String name = System.currentTimeMillis() + ".xml";
        FileOutputStream file = new FileOutputStream(name);
        IOUtils.copy(in, file);
        in = new FileInputStream(name);
    }
    //FileOutputStream temp = new FileOutputStream("temp.xml");
    //org.apache.commons.io.IOUtils.copy(in, temp);
    //temp.close();
    //in.close();
    //in = new FileInputStream("temp.xml");
    ParseParams params = new ParseParams();
    params.setRegistry(this);
    StructureType st = SdmxIO.parseStructure(params, in);
    if (st == null) {
        System.out.println("St is null!");
    } else if (SdmxIO.isSaveXml()) {
        String name = System.currentTimeMillis() + "-21.xml";
        FileOutputStream file = new FileOutputStream(name);
        Sdmx21StructureWriter.write(st, file);
    }
    return st;
}