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:sdmx.net.service.knoema.KnoemaRESTServiceRegistry.java

private StructureType retrieve(String urlString) throws MalformedURLException, IOException, ParseException {
    System.out.println("Retrieve:" + urlString);
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }// w  w  w  .j a  v  a2s  .com
    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");
    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!");
    } else {
        if (SdmxIO.isSaveXml()) {
            String name = System.currentTimeMillis() + "-21.xml";
            FileOutputStream file = new FileOutputStream(name);
            Sdmx21StructureWriter.write(st, file);
        }
    }
    return st;
}

From source file:com.amazonaws.http.UrlHttpClient.java

@SuppressWarnings("checkstyle:emptyblock")
HttpResponse createHttpResponse(final HttpRequest request, final HttpURLConnection connection)
        throws IOException {
    // connection.setDoOutput(true);
    final String statusText = connection.getResponseMessage();
    final int statusCode = connection.getResponseCode();
    InputStream content = connection.getErrorStream();
    if (content == null) {
        // HEAD method doesn't have a body
        if (!"HEAD".equals(request.getMethod())) {
            try {
                content = connection.getInputStream();
            } catch (final IOException ioe) {
                // getInputStream() can throw an exception when there is no
                // input stream.
            }/*from  w  w  w .j  ava  2s.c o m*/
        }
    }

    final HttpResponse.Builder builder = HttpResponse.builder().statusCode(statusCode).statusText(statusText)
            .content(content);
    for (final Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        // skip null field that stores connection status
        if (header.getKey() == null) {
            continue;
        }
        // No AWS service return a list of header values, so it's safe to
        // take the first one.
        builder.header(header.getKey(), header.getValue().get(0));
    }

    return builder.build();
}

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

public void delete() throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("DELETE");
    int code = con.getResponseCode();
    if (code != 200 && code != 204) {
        Assert.assertEquals(con.getResponseMessage(), 204, code);
    }// w w w .  j  a  va 2s . co  m
}

From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java

public void testQueryStatus() throws Exception {
    URL url = new URI("http", null, "localhost", HTTP_SERVER_PORT, "/path", "status=303 See Other", null)
            .toURL();//from   w  ww.  j av a 2 s.co m
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.connect();
    assertEquals(303, conn.getResponseCode());
    assertEquals("See Other", conn.getResponseMessage());
}

From source file:com.couchbase.client.vbucket.ConfigurationProviderHTTP.java

/**
 * Helper method that reads content from URLConnection to the string.
 *
 * @param connection a given URLConnection
 * @return content string//from ww w.ja  v a  2  s.  c  o  m
 * @throws IOException
 */
private String readToString(URLConnection connection) throws IOException {
    BufferedReader reader = null;
    try {
        InputStream inStream = connection.getInputStream();
        if (connection instanceof java.net.HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            if (httpConnection.getResponseCode() == 403) {
                throw new IOException("Service does not accept the authentication " + "credentials: "
                        + httpConnection.getResponseCode() + httpConnection.getResponseMessage());
            } else if (httpConnection.getResponseCode() >= 400) {
                throw new IOException("Service responded with a failure code: "
                        + httpConnection.getResponseCode() + httpConnection.getResponseMessage());
            }
        } else {
            throw new IOException("Unexpected URI type encountered");
        }
        reader = new BufferedReader(new InputStreamReader(inStream));
        String str;
        StringBuilder buffer = new StringBuilder();
        while ((str = reader.readLine()) != null) {
            buffer.append(str);
        }
        return buffer.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:sdmx.net.service.wb.WBRESTServiceRegistry.java

private StructureType retrieve2(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").info("ILORestServiceRegistry: retrieve " + urlString);
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }/*from   ww w . j a  v  a2 s  . c  o m*/
    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:net.solarnetwork.node.setup.web.SolarInHttpProxy.java

/**
 * Proxy an HTTP request to SolarIn and return the result on a given HTTP
 * response./*w w w  .  ja  va2 s  .  c o  m*/
 * 
 * @param request
 *        the request to proxy
 * @param response
 *        the response to return the proxy response to
 * @throws IOException
 *         if an IO error occurs
 */
@RequestMapping(value = { "/api/v1/sec/location", "/api/v1/sec/location/price",
        "/api/v1/sec/location/weather" }, method = RequestMethod.GET)
public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String context = request.getContextPath();
    String path = request.getRequestURI();
    if (path.startsWith(context)) {
        path = path.substring(context.length());
    }
    String query = request.getQueryString();
    String url = getIdentityService().getSolarInBaseUrl() + path;
    if (query != null) {
        url += '?' + query;
    }
    String accept = request.getHeader("Accept");
    if (accept == null) {
        accept = ACCEPT_JSON;
    }
    try {
        URLConnection conn = getURLConnection(url, request.getMethod(), accept);
        if (conn instanceof HttpURLConnection) {
            final HttpURLConnection httpConn = (HttpURLConnection) conn;
            for (Map.Entry<String, List<String>> me : httpConn.getHeaderFields().entrySet()) {
                final String headerName = me.getKey();
                if (headerName == null) {
                    continue;
                }
                for (String val : me.getValue()) {
                    response.addHeader(headerName, val);
                }
            }
            final String msg = httpConn.getResponseMessage();
            if (msg != null && !msg.equalsIgnoreCase("OK")) {
                response.sendError(httpConn.getResponseCode(), msg);
            } else {
                response.setStatus(httpConn.getResponseCode());
            }
        }
        FileCopyUtils.copy(conn.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        log.debug("Error proxying SolarIn URL [{}]", url, e);
        response.sendError(502, "Problem communicating with SolarIn: " + e.getMessage());
    }
}

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

protected void deleteToscaDeployment(String toscaUUID) {
    StringBuilder deployment = new StringBuilder();
    HttpURLConnection conn;
    try {//from  w w  w .  j ava  2 s.  co m
        URL deploymentEndpoint = new URL(endpoint.toString() + "/" + toscaUUID);
        conn = (HttpURLConnection) deploymentEndpoint.openConnection();
        conn.setRequestMethod("DELETE");
        log.debug("Orchestrator status code: " + conn.getResponseCode());
        log.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == 204) {
            log.debug("Successfully removed resource: '" + toscaUUID + "'");
        } else {
            log.error("Unable to remove resource: '" + toscaUUID + "'");
        }
    } catch (IOException ex) {
        log.error("Connection error with the service at " + endpoint.toString());
        log.error(ex);
    }
}

From source file:sdmx.net.service.opensdmx.OpenSDMXRESTQueryable.java

private StructureType retrieve(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").log(Level.INFO, "Rest Queryable Retrieve:" + urlString);
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }/*from w  w  w .j  a  v a  2  s . c  o m*/
    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");
    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!");
    } else {
        if (SdmxIO.isSaveXml()) {
            String name = System.currentTimeMillis() + "-21.xml";
            FileOutputStream file = new FileOutputStream(name);
            Sdmx21StructureWriter.write(st, file);
        }
    }
    return st;
}

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

public byte[] get(String type) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept", type);
    con.setRequestProperty("Accept-Encoding", "gzip");
    Assert.assertEquals(con.getResponseMessage(), 200, con.getResponseCode());
    InputStream in = con.getInputStream();
    try {/*from  w  w w . j a  va2  s .  c  om*/
        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();
    }
}