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:bluevia.examples.MODemo.java

/**
 * @param args//from  ww w.j a v  a2  s  .c  o  m
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:GetURLInfo.java

/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
    URLConnection c = url.openConnection(); // Get URLConnection from URL
    c.connect(); // Open a connection to URL

    // Display some information about the URL contents
    System.out.println("  Content Type: " + c.getContentType());
    System.out.println("  Content Encoding: " + c.getContentEncoding());
    System.out.println("  Content Length: " + c.getContentLength());
    System.out.println("  Date: " + new Date(c.getDate()));
    System.out.println("  Last Modified: " + new Date(c.getLastModified()));
    System.out.println("  Expiration: " + new Date(c.getExpiration()));

    // If it is an HTTP connection, display some additional information.
    if (c instanceof HttpURLConnection) {
        HttpURLConnection h = (HttpURLConnection) c;
        System.out.println("  Request Method: " + h.getRequestMethod());
        System.out.println("  Response Message: " + h.getResponseMessage());
        System.out.println("  Response Code: " + h.getResponseCode());
    }/*ww w  . j  a  va 2  s.  com*/
}

From source file:org.apache.oodt.cas.protocol.http.util.HttpUtils.java

public static HttpURLConnection connect(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.connect();/*from   w  w w .  j  a  v a 2s . c  om*/
    conn.getResponseMessage();
    return conn;
}

From source file:Main.java

@SuppressLint("NewApi")
public static void getURL(String path) {
    String fileName = "";
    String dir = "/IndoorNavi/";
    File sdRoot = Environment.getExternalStorageDirectory();
    try {//from w  w w. j  a  va  2s .  c  o  m
        // Open the URLConnection for reading
        URL u = new URL(path);
        // URL u = new URL("http://www.baidu.com/");
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();

        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        //System.out.println("HTTP/1.x " + code + " " + response);
        for (int j = 1;; j++) {
            String key = uc.getHeaderFieldKey(j);
            String header = uc.getHeaderField(j);
            if (!(key == null)) {
                if (key.equals("Content-Name"))
                    fileName = header;
            }
            if (header == null || key == null)
                break;
            //System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
        }
        Log.i("zhr", fileName);
        //System.out.println();

        try (InputStream in = new BufferedInputStream(uc.getInputStream())) {

            // chain the InputStream to a Reader
            Reader r = new InputStreamReader(in);
            int c;
            File mapFile = new File(sdRoot, dir + fileName);
            mapFile.createNewFile();
            FileOutputStream filecon = new FileOutputStream(mapFile);
            while ((c = r.read()) != -1) {
                //System.out.print((char) c);
                filecon.write(c);
                filecon.flush();

            }
            filecon.close();
        }

    } catch (MalformedURLException ex) {
        System.err.println(path + " is not a parseable URL");
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:Main.java

public static String requestPage(String urlPath) throws Exception {
    URL url = new URL(urlPath);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new Exception("Error loading page: " + responseCode + connection.getResponseMessage());
    }//from  ww w. ja  va 2  s .com

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    String response = "";

    while ((inputLine = in.readLine()) != null) {
        response += inputLine;
    }

    in.close();
    return response;
}

From source file:Main.java

@SuppressWarnings("unused")
public static void selectServer2() {
    for (String host : host_arr) {
        HttpURLConnection conn = null;
        try {//from  ww  w .ja  va2s . c  om
            conn = (HttpURLConnection) new URL(host).openConnection();
            conn.setConnectTimeout(6000);
            int result = conn.getResponseCode();
            String re = conn.getResponseMessage();
            if (result == HttpURLConnection.HTTP_OK) {
                HOST = host;//
                break;
            } else {
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

    }
}

From source file:org.apache.roller.weblogger.util.MediacastUtil.java

/**
 * Validate a Mediacast resource./*from  w  ww . j ava  2 s .c  o m*/
 */
public static final MediacastResource lookupResource(String url) throws MediacastException {

    if (url == null || url.trim().length() == 0) {
        return null;
    }

    MediacastResource resource = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        int response = con.getResponseCode();
        String message = con.getResponseMessage();

        if (response != 200) {
            log.debug("Mediacast error " + response + ":" + message + " from url " + url);
            throw new MediacastException(BAD_RESPONSE, "weblogEdit.mediaCastResponseError");
        } else {
            String contentType = con.getContentType();
            long length = con.getContentLength();

            if (contentType == null || length == -1) {
                log.debug("Response valid, but contentType or length is invalid");
                throw new MediacastException(INCOMPLETE, "weblogEdit.mediaCastLacksContentTypeOrLength");
            }

            resource = new MediacastResource(url, contentType, length);
            log.debug("Valid mediacast resource = " + resource.toString());

        }
    } catch (MalformedURLException mfue) {
        log.debug("Malformed MediaCast url: " + url);
        throw new MediacastException(BAD_URL, "weblogEdit.mediaCastUrlMalformed", mfue);
    } catch (Exception e) {
        log.error("ERROR while checking MediaCast URL: " + url + ": " + e.getMessage());
        throw new MediacastException(CHECK_FAILED, "weblogEdit.mediaCastFailedFetchingInfo", e);
    }
    return resource;
}

From source file:com.baidu.api.client.core.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl         The Url to be downloaded.
 * @param connectTimeout Connect timeout in milliseconds.
 * @param readTimeout    Read timeout in milliseconds.
 * @param maxFileSize    Max file size in BYTE.
 * @return The file content as byte array.
 *///w  ww  .j av  a2  s .  co m
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        throw new ClientInternalException(msg);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ?
            System.out.println("Exception while close url - " + e.getMessage());
        }
    }
}

From source file:org.alex73.osm.monitors.export.ReadChangesets.java

/**
 *  URL./*from  w  w w.j  a  v  a  2s  . c  o m*/
 */
static byte[] get(String url) throws Exception {
    System.out.println("Load " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException("Call " + url + ": " + conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    try {
        try (InputStream in = conn.getInputStream()) {
            return IOUtils.toByteArray(in);
        }
    } finally {
        conn.disconnect();
    }
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static String summariseHttpErrorResponse(final HttpURLConnection connection) throws IOException {
    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_NOT_FOUND)
        return String.format("HTTP %s %s", responseCode, connection.getResponseMessage());
    return String.format("HTTP %s %s: %s", responseCode, connection.getResponseMessage(),
            IoHelper.toString(connection.getErrorStream(), MAX_ERR_BODY_LENGTH_CHAR));
}