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:org.elasticsearch.metrics.ElasticsearchReporter.java

private void closeConnection(HttpURLConnection connection) throws IOException {
    connection.getOutputStream().close();
    connection.disconnect();//from  w  w w  . j  ava 2  s  .  com

    // 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() != 200) {
        LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(),
                connection.getResponseMessage());
    }
}

From source file:com.fluidops.iwb.provider.CkanProvider.java

@Override
public void gather(List<Statement> res) throws Exception {
    // Read CKAN location and establish connection
    URL registryUrl = new URL(config.location);
    HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection();
    registryConnection.setRequestMethod("GET");

    // Check if connection to CKAN could be established
    if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        String msg = String.format("Connection to the CKAN registry could not be established. (%s, %s)",
                registryConnection.getResponseCode(), registryConnection.getResponseMessage());
        logger.info(msg);/*from   w ww  . j  a  va 2s.c  o m*/
        throw new IllegalStateException(msg);
    }
    logger.trace("Connection to CKAN established successfully.");

    String siteContent = GenUtil.readUrl(registryConnection.getInputStream());

    JSONObject groupAsJson = null;
    JSONArray packageListJsonArray = null;
    try {
        groupAsJson = new JSONObject(new JSONTokener(siteContent));
        packageListJsonArray = groupAsJson.getJSONArray("packages");
    } catch (JSONException e) {
        String msg = String.format("Returned content %s is not valid JSON. Check if the registry URL is valid.",
                siteContent);
        logger.debug(msg);
        throw new IllegalStateException(msg);
    }
    logger.trace("Extracted JSON from CKAN successfully");

    // Create metadata about LOD catalog
    res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG));
    res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDFS.LABEL, CKAN.CKAN_CATALOG_LABEL));

    // Extract metadata for individual data sets listed in CKAN
    MultiThreadedHttpConnectionManager connectionManager = null;
    ExecutorService pool = null;
    try {
        pool = Executors.newFixedThreadPool(10);
        connectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(connectionManager);

        List<Statement> synchedList = Collections.synchronizedList(res);
        for (int i = 0; i < packageListJsonArray.length(); i++) {
            String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString();
            String baseUri = findBaseUri(
                    "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString());
            baseUri = (baseUri == null) ? host : baseUri;
            pool.execute(new MetadataReader(client, host, baseUri, CKAN.CKAN_CATALOG, synchedList));
        }
    } finally {
        if (pool != null) {
            pool.shutdown();
            pool.awaitTermination(4, TimeUnit.HOURS);
        }
        if (connectionManager != null)
            connectionManager.shutdown();
    }
}

From source file:com.android.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }/*from ww  w.  j ava  2  s  .co m*/
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:com.ibm.datapower.amt.clientAPI.Blob.java

/**
 * Get the contents of the blob as an InputStream.
 * <p>/* w  w w .jav a  2 s .c  o m*/
 * If the Blob was initially constructed via a File, this will open the file
 * and return the InputStream pointing at the beginning of the file. It is
 * up to the caller to close the InputStream.
 * <p>
 * If the Blob was initially constructed via a byte array, this will wrap
 * the byte array with an InputStream. No file is actually created, and the
 * byte array is not copied. For good measure, the caller should close the
 * InputStream.
 * <p>
 * This method needs to be public so it can be invoked by the dataAPI.
 * 
 * @return an InputStream representation of the binary data
 * @throws IOException
 *             there was a problem reading the file from the disk.
 */
public InputStream getInputStream() throws IOException {
    final String METHOD_NAME = "getInputStream"; //$NON-NLS-1$
    InputStream result = null;
    if (this.file != null) {
        result = new FileInputStream(this.file);
    } else if (this.url != null) {
        CustomURLConnection customURLConn = new CustomURLConnection(this.url);
        logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME,
                "Connect timeout is set to " + customURLConn.getConnectLimit());
        URLConnection connection = customURLConn.openConnection();
        if (connection == null) {
            String message = Messages.getString("wamt.clientAPI.Blob.connectionErr", this.url.getHost());
            IOException e = new IOException(message);
            logger.throwing(CLASS_NAME, METHOD_NAME, e);
            throw e;
        }

        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            result = url.openStream();
        } else {
            // fix for 13324: Firmware images reported as not real, when using URL behind some form of authentication              
            throw (new IOException(Integer.toString(httpConnection.getResponseCode()) + " - "
                    + httpConnection.getResponseMessage()));
        }
    } else if (this.bytes != null) {
        result = new ByteArrayInputStream(this.bytes);
    } else {
        // this should not happen
        logger.logp(Level.INFO, CLASS_NAME, METHOD_NAME,
                Messages.getString("wamt.clientAPI.Blob.internalErr", this.toString())); //$NON-NLS-1$
    }
    return (result);
}

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

@Override
public Status upload(SQLiteDatabase db, final long mID) {
    Status s;//from w  w w .  j av a 2 s .com
    if ((s = connect()) != Status.OK) {
        return s;
    }

    String URL = IMPORT_URL + "?access_token=" + access_token;
    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(URL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Encoding", "gzip");
        OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream()));
        out.write(writer.toString().getBytes());
        out.flush();
        out.close();
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        Log.e(getName(), "code: " + responseCode + ", amsg: " + amsg);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        JSONObject obj = SyncHelper.parse(in);
        JSONObject data = obj.getJSONObject("data");

        boolean found = false;
        if (found == false) {
            try {
                found = data.getJSONArray("workoutIds").length() == 1;
            } catch (JSONException e) {
            }
        }
        if (found == false) {
            try {
                found = data.getJSONArray("ids").length() == 1;
            } catch (JSONException e) {
            }
        }
        if (!found) {
            Log.e(getName(), "Unhandled response from RunningAHEADSynchronizer: " + obj);
        }
        if (responseCode == HttpStatus.SC_OK && found) {
            conn.disconnect();
            return Status.OK;
        }
        ex = new Exception(amsg);
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.apache.oozie.client.OozieClient.java

static void handleError(HttpURLConnection conn) throws IOException, OozieClientException {
    int status = conn.getResponseCode();
    String error = conn.getHeaderField(RestConstants.OOZIE_ERROR_CODE);
    String message = conn.getHeaderField(RestConstants.OOZIE_ERROR_MESSAGE);

    if (error == null) {
        error = "HTTP error code: " + status;
    }//w w w  .  ja  v a  2 s . c  om

    if (message == null) {
        message = conn.getResponseMessage();
    }
    throw new OozieClientException(error, message);
}

From source file:com.commsen.jwebthumb.WebThumbService.java

private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest)
        throws WebThumbException {
    Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!");
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest);
    }/*from  w w  w .  ja  va 2s . com*/
    WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest);

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream());

        int responseCode = connection.getResponseCode();
        String contentType = getContentType(connection);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " "
                    + connection.getResponseMessage());
            LOGGER.fine("Content type: " + contentType);
        }

        if (responseCode == HttpURLConnection.HTTP_OK) {
            if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) {
                throw new WebThumbException(
                        "Server side error: " + IOUtils.toString(connection.getInputStream()));
            }
            return connection;
        } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(),
                    WebThumbResponse.class);
            throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue());
        } else {
            throw new WebThumbException("Server side error: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage());
        }

    } catch (MalformedURLException e) {
        throw new WebThumbException("failed to send request", e);
    } catch (IOException e) {
        throw new WebThumbException("failed to send request", e);
    }

}

From source file:com.vincestyling.netroid.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//from  ww w .ja  va 2 s.c om
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;/*  w  w w  . jav  a2 s  . com*/

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}