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:com.truebanana.http.HTTPResponse.java

protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) {
    HTTPResponse response = new HTTPResponse();

    response.originalRequest = request;/*w  w  w  . ja  va 2  s  .  co  m*/
    if (content != null) {
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[16384];
            int nRead;

            while ((nRead = content.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            response.content = buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        response.statusCode = connection.getResponseCode();
    } catch (IOException e) {
    }

    String message = null;
    try {
        message = connection.getResponseMessage();
    } catch (IOException e) {
        message = e.getLocalizedMessage();
    }
    response.responseMessage = response.statusCode + (message != null ? " " + message : "");

    response.headers = connection.getHeaderFields();

    response.requestURL = connection.getURL().toString();

    return response;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset/* w w w  . j  av  a 2s .  co m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:org.jboss.pnc.buildagent.server.TestGetRunningProcesses.java

@Test
public void getRunningProcesses() throws Exception {
    String terminalUrl = "http://" + HOST + ":" + PORT;

    HttpURLConnection connection = retrieveProcessList();
    Assert.assertEquals(connection.getResponseMessage(), 200, connection.getResponseCode());

    JsonNode node = readResponse(connection);
    Assert.assertEquals(0, node.size());

    String context = this.getClass().getName() + ".getRunningProcesses";

    ObjectWrapper<Boolean> resultReceived = new ObjectWrapper<>(false);
    Consumer<TaskStatusUpdateEvent> onStatusUpdate = (statusUpdateEvent) -> {
        if (statusUpdateEvent.getNewStatus().equals(Status.RUNNING)) {
            try {
                HttpURLConnection afterExecution = retrieveProcessList();
                Assert.assertEquals(afterExecution.getResponseMessage(), 200, afterExecution.getResponseCode());
                JsonNode nodeAfterExecution = readResponse(afterExecution);
                Assert.assertEquals(1, nodeAfterExecution.size());
                resultReceived.set(true);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }//from w  ww .  ja  v  a 2s.  com
        }
    };

    BuildAgentClient buildAgentClient = new BuildAgentClient(terminalUrl, Optional.empty(), onStatusUpdate,
            context);
    buildAgentClient.executeCommand(TEST_COMMAND);

    Supplier<Boolean> evaluationSupplier = () -> resultReceived.get();
    Wait.forCondition(evaluationSupplier, 10, ChronoUnit.SECONDS,
            "Client was not connected within given timeout.");
    buildAgentClient.close();
}

From source file:Main.java

public Main() {
    JPanel inputPanel = new JPanel(new BorderLayout(3, 3));
    go.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                URL pageURL = new URL("http://www.google.com");
                HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection();
                int respCode = urlConnection.getResponseCode();
                String response = urlConnection.getResponseMessage();
                codeArea.setText("HTTP/1.x " + respCode + " " + response + "\n");
                int count = 1;
                while (true) {
                    String header = urlConnection.getHeaderField(count);
                    String key = urlConnection.getHeaderFieldKey(count);
                    if (header == null || key == null) {
                        break;
                    }/* www  .  ja  v a2  s.c  o  m*/
                    codeArea.append(urlConnection.getHeaderFieldKey(count) + ": " + header + "\n");
                    count++;
                }
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                Reader r = new InputStreamReader(in);
                int c;
                while ((c = r.read()) != -1) {
                    codeArea.append(String.valueOf((char) c));
                }
                codeArea.setCaretPosition(1);
            } catch (Exception ee) {
            }
        }
    });
    inputPanel.add(BorderLayout.EAST, go);
    JScrollPane codeScroller = new JScrollPane(codeArea);
    add(BorderLayout.NORTH, inputPanel);
    add(BorderLayout.CENTER, codeScroller);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700, 500);
    this.setVisible(true);
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Makes an HTTP POST to an URL sending an body. The URL and body are
 * represented as String.//w w  w. jav  a 2  s.  c o m
 *
 * @param urlStr String representation of the URL
 * @param content Styring representation of the body to post
 *
 * @return if the request has been accompished
 */

public static boolean DoHTTPPost(String urlStr, String content) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID));
        urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD));
        urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD));
        urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD));

        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.info("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me);
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe);
        return false;
    }
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *///w  ww .  java 2s.  c om
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        urlConnection.connect();
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } catch (IOException e) {
        String details;
        if (urlConnection != null) {
            details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage()
                    + ")";
        } else {
            details = "";
        }
        Log.e("ExoplayerUtil", "executePost: Request failed" + details, e);
        throw e;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:it.polito.tellmefirst.enhancer.NYTimesEnhancer.java

private String getResultFromAPI(String urlStr) {
    LOG.debug("[getResultFromAPI] - BEGIN");
    String result = "";
    try {//w ww  . ja v  a 2  s  . c o m
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        result = sb.toString();
    } catch (Exception e) {
        LOG.error("[getResultFromAPI] - EXCEPTION: ", e);
    }
    LOG.debug("[getResultFromAPI] - END");
    return result;
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * Validates the status of an <code>HttpURLConnection</code> against an expected HTTP
 * status code. If the current status code is not the expected one it throws an exception
 * with a detail message using Server side error messages if available.
 *
 * @param conn the <code>HttpURLConnection</code>.
 * @param expected the expected HTTP status code.
 * @throws IOException thrown if the current status code does not match the expected one.
 *///from  w w w.j  a  v  a2s. co m
private static void validateResponse(HttpURLConnection conn, int expected) throws IOException {
    int status = conn.getResponseCode();
    if (status != expected) {
        try {
            JSONObject json = (JSONObject) jsonParse(conn);
            throw new IOException(MessageFormat.format("HTTP status [{0}], {1} - {2}", json.get("status"),
                    json.get("reason"), json.get("message")));
        } catch (IOException ex) {
            if (ex.getCause() instanceof IOException) {
                throw (IOException) ex.getCause();
            }
            throw new IOException(
                    MessageFormat.format("HTTP status [{0}], {1}", status, conn.getResponseMessage()));
        }
    }
}

From source file:it.polito.tellmefirst.enhancer.BBCEnhancer.java

public String getResultFromAPI(String urlStr, String type) {

    LOG.debug("[getResultFromAPI] - BEGIN");
    String result = "";
    try {/*from  w  w  w  .  j  a va 2 s. com*/
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", type);
        if (conn.getResponseCode() != 200) {
            System.out.println(conn.getResponseMessage());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        result = sb.toString();
    } catch (Exception e) {
        LOG.error("[getResultFromAPI] - EXCEPTION: ", e);
    }
    LOG.debug("[getResultFromAPI] - END");
    return result;
}

From source file:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {/*w  w w  .j a  v  a2 s  .  c  om*/

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}