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.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

private Response fetchResponse(HttpURLConnection connection) throws IOException {

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }/*www  .  j  av  a 2 s  .c  o  m*/
    // ??
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    // response
    Response response = new Response(responseStatus);
    // response?
    response.setEntity(entityFromURLConnwction(connection));
    addHeadersToResponse(response, connection);
    return response;
}

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

public String getRedirectLocation() throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("HEAD");
    int code = con.getResponseCode();
    if (!(code == 301 || code == 303 || code == 302 || code == 307 || code == 308))
        Assert.assertEquals(con.getResponseMessage(), 302, code);
    return con.getHeaderField("Location");
}

From source file:edu.wfu.inotado.helper.RestClientHelper.java

public String getFromService(String serviceName, String urlStr) throws Exception {

    OAuthConsumer consumer = oauthHelper.getConsumer(serviceName);
    URL url;//from   www.  j a v a2s.  c om
    url = new URL(urlStr);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    log.info("Sending request...");
    request.connect();

    InputStream in = (InputStream) request.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String result, line = reader.readLine();
    result = line;
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    log.debug("Respone: " + result);
    log.info("Response: " + request.getResponseCode() + " " + request.getResponseMessage());

    return result;
}

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

public void testStatus() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-ResponseStatus", "302 Temporary Redirect");
    conn.connect();/*from  w w  w .  j a  va  2 s  .c om*/
    assertEquals(302, conn.getResponseCode());
    assertEquals("Temporary Redirect", conn.getResponseMessage());
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public Path download(ChromiumVersion version) {
    final Path destinationRoot = getChromiumPath(version);
    final Path executable = getExecutable(version);

    String url;//from www. j  a v a 2 s .  c o m
    if (WINDOWS) {
        url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (LINUX) {
        url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (MAC) {
        url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision());
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("HEAD");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }
        long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0);
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r"
                + version.getRevision() + ".zip";
        Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName);
        if (exists(archive) && contentLength != size(archive)) {
            delete(archive);
        }
        if (!exists(archive)) {
            logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%");
            u = new URL(url);
            if (conn.getResponseCode() != 200) {
                throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            Thread thread = null;
            AtomicBoolean halt = new AtomicBoolean(false);
            Runnable progress = () -> {
                try {
                    long fileSize = size(archive);
                    logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(),
                            round((fileSize * 100L) / contentLength));
                } catch (IOException e) {
                    // ignore
                }
            };
            try (InputStream is = conn.getInputStream()) {
                logger.info("Download location: " + archive.toString());
                thread = new Thread(() -> {
                    while (true) {
                        try {
                            if (halt.get()) {
                                break;
                            }
                            progress.run();
                            sleep(1000);
                        } catch (Throwable e) {
                            // ignore
                        }
                    }
                });
                thread.setName("cdp4j");
                thread.setDaemon(true);
                thread.start();
                copy(conn.getInputStream(), archive);
            } finally {
                if (thread != null) {
                    progress.run();
                    halt.set(true);
                }
            }
        }
        logger.info("Extracting to: " + destinationRoot.toString());
        if (exists(archive)) {
            createDirectories(destinationRoot);
            unpack(archive.toFile(), destinationRoot.toFile());
        }

        if (!exists(executable) || !isExecutable(executable)) {
            throw new CdpException("Chromium executable not found: " + executable.toString());
        }

        if (!WINDOWS) {
            Set<PosixFilePermission> permissions = getPosixFilePermissions(executable);
            if (!permissions.contains(OWNER_EXECUTE)) {
                permissions.add(OWNER_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
            if (!permissions.contains(GROUP_EXECUTE)) {
                permissions.add(GROUP_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
        }
    } catch (IOException e) {
        throw new CdpException(e);
    }
    return executable;
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static JSONObject getRemoteIndex(String path) throws MPTException {
    try {/*from   w ww.  j  a va  2s  .co m*/
        URL url = new URL(path + (!path.endsWith("/") ? "/" : "") + "mpt.json"); // get URL object for data file
        URLConnection conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection http = (HttpURLConnection) conn; // cast the connection
            int response = http.getResponseCode(); // get the response
            if (response >= 200 && response <= 299) { // verify the remote isn't upset at us
                InputStream is = http.getInputStream(); // open a stream to the URL
                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // get a reader
                JSONParser parser = new JSONParser(); // get a new parser
                String line;
                StringBuilder content = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    content.append(line);
                JSONObject json = (JSONObject) parser.parse(content.toString()); // parse JSON object
                // vefify remote config is valid
                if (json.containsKey("packages") && json.get("packages") instanceof JSONObject) {
                    return json;
                } else
                    throw new MPTException(
                            ERROR_COLOR + "Index for repository at " + path + "is missing required elements!");
            } else {
                String error = ERROR_COLOR + "Remote returned bad response code! (" + response + ")";
                if (!http.getResponseMessage().isEmpty())
                    error += " The remote says: " + ChatColor.GRAY + ChatColor.ITALIC
                            + http.getResponseMessage();
                throw new MPTException(error);
            }
        } else
            throw new MPTException(ERROR_COLOR + "Bad protocol for URL!");
    } catch (MalformedURLException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot parse URL!");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot open connection to URL!");
    } catch (ParseException ex) {
        throw new MPTException(ERROR_COLOR + "Repository index is not valid JSON!");
    }
}

From source file:sdmx.net.service.insee.INSEERESTQueryable.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());
    }/* w w  w .j av 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");
    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.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java

private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod)
        throws ConnectionException {
    HttpURLConnection urlConnection;
    try {//from w w w  .  ja va  2s .c om
        URIBuilder b = new URIBuilder(BASE_URL);
        b.addParameters(params);
        URL url = b.build().toURL();
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(responseMethod);
        urlConnection.setReadTimeout(TIME_OUT_LENGTH);
        urlConnection.setConnectTimeout(TIME_OUT_LENGTH);
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(urlConnection.getResponseMessage());
        return urlConnection;
    } catch (URISyntaxException | IOException ex) {
        throw new ConnectionException(ex);
    }
}

From source file:edu.wfu.inotado.helper.OAuthHelper.java

@Deprecated
public void sendRequest(AuthStore authStore) throws Exception {
    OAuthConsumer consumer = cacheHelper.getFromCache(authStore.getSystemName(), consumerCache);
    URL url;/*from  w ww . j  a  va  2 s .c  o m*/
    url = new URL("https://vigrior.schoolchapters.com/api/v1/courses.json");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    System.out.println("Sending request...");
    request.connect();
    System.out.println(request.getContent());

    InputStream in = (InputStream) request.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String result, line = reader.readLine();
    result = line;
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    System.out.println(result);
    System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage());

}

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

public void post(String type, byte[] body) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", type);
    con.setDoOutput(true);/* w w w  . j  a v a 2 s.  co m*/
    OutputStream req = con.getOutputStream();
    try {
        req.write(body);
    } finally {
        req.close();
    }
    Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode());
}