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.nomis.NOMISRESTServiceRegistry.java

private StructureType retrieve3(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").info("NOMISRestServiceRegistry: retrieve3 " + urlString);
    String s = options;/*from www .  java 2 s.  c  o  m*/
    if (urlString.indexOf("?") == -1) {
        s = "?" + s + "&random=" + System.currentTimeMillis();
    } else {
        s = "&" + s + "&random=" + System.currentTimeMillis();
        ;
    }

    URL url = new URL(urlString + s);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    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();
    StructureType st = SdmxIO.parseStructure(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:co.aikar.timings.TimingsExport.java

private String getResponse(HttpURLConnection con) throws IOException {
    InputStream is = null;/* w  ww. jav a  2s.co m*/
    try {
        is = con.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte[] b = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(b)) != -1) {
            bos.write(b, 0, bytesRead);
        }
        return bos.toString();

    } catch (IOException ex) {
        listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
        Bukkit.getLogger().log(Level.WARNING, con.getResponseMessage(), ex);
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

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

@Override
public Status getFeed(FeedUpdater feedUpdater) {
    Status s;/*from  w ww. j a v  a2  s  .  c om*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    StringBuilder url = new StringBuilder();
    url.append(FEED_URL).append("?authToken=").append(authToken);
    url.append("&maxResults=25");

    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setRequestMethod(RequestMethod.GET.name());
        final InputStream in = new BufferedInputStream(conn.getInputStream());
        final JSONObject reply = SyncHelper.parse(in);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();

        conn.disconnect();

        if (responseCode == HttpStatus.SC_OK) {
            parseFeed(feedUpdater, reply);
            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.runnerup.export.GarminSynchronizer.java

private Status connectOld() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;//from  ww  w.  j  a  v a  2 s  .  co m
    s.authMethod = Synchronizer.AuthMethod.USER_PASS;

    HttpURLConnection conn = null;

    /**
     * connect to START_URL to get cookies
     */
    conn = (HttpURLConnection) new URL(START_URL).openConnection();
    {
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        if (responseCode != HttpStatus.SC_OK) {
            Log.e(getName(), "GarminSynchronizer::connect() - got " + responseCode + ", msg: " + amsg);
        }
    }
    conn.disconnect();

    /**
     * Then login using a post
     */
    String login = LOGIN_URL;
    FormValues kv = new FormValues();
    kv.put("login", "login");
    kv.put("login:loginUsernameField", username);
    kv.put("login:password", password);
    kv.put("login:signInButton", "Sign In");
    kv.put("javax.faces.ViewState", "j_id1");

    conn = (HttpURLConnection) new URL(login).openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);

    {
        OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
        kv.write(wr);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        Log.e(getName(), "code: " + responseCode + ", msg=" + amsg);
        getCookies(conn);
    }
    conn.disconnect();

    /**
     * An finally check that all is OK
     */
    return checkLogin();
}

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

@Override
public Status connect() {
    Status s = Status.NEED_AUTH;/*from w  w w. j  a  va  2  s  .co  m*/
    s.authMethod = Synchronizer.AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    if (isConnected) {
        return Status.OK;
    }

    Exception ex = null;
    HttpURLConnection conn = null;
    logout();

    try {
        conn = (HttpURLConnection) new URL(CHOOSE_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);

        Log.e(getName(), "GarminSynchronizer.connect() CHOOSE_URL => code: " + responseCode + ", msg: " + amsg);

        if (responseCode == HttpStatus.SC_OK) {
            return connectOld();
        } else if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            return connectNew();
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

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

From source file:hudson.FilePathTest.java

@Issue("JENKINS-26196")
@Test//from  w  w  w.  j  a  v  a2 s .  c o  m
public void installIfNecessarySkipsDownloadWhenErroneous() throws Exception {
    File tmp = temp.getRoot();
    final FilePath d = new FilePath(tmp);
    d.child(".timestamp").touch(123000);
    final HttpURLConnection con = mock(HttpURLConnection.class);
    final URL url = someUrlToZipFile(con);
    when(con.getResponseCode()).thenReturn(HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
    when(con.getResponseMessage()).thenReturn("Gateway Timeout");
    when(con.getInputStream()).thenThrow(new ConnectException());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String message = "going ahead";
    assertFalse(d.installIfNecessaryFrom(url, new StreamTaskListener(baos), message));
    verify(con).setIfModifiedSince(123000);
    String log = baos.toString();
    assertFalse(log, log.contains(message));
    assertTrue(log, log.contains("504 Gateway Timeout"));
}

From source file:freemarker.test.servlet.WebAppTestCase.java

protected final HTTPResponse getHTTPResponse(String webAppName, String webAppRelURL) throws Exception {
    if (webAppName.startsWith("/") || webAppName.endsWith("/")) {
        throw new IllegalArgumentException("\"webAppName\" can't start or end with \"/\": " + webAppName);
    }/*from ww w. j a v  a2s .com*/
    if (webAppRelURL.startsWith("/") || webAppRelURL.endsWith("/")) {
        throw new IllegalArgumentException("\"webappRelURL\" can't start or end with \"/\": " + webAppRelURL);
    }

    ensureWebAppIsDeployed(webAppName);

    final URI uri = new URI("http://localhost:" + server.getConnectors()[0].getLocalPort() + "/" + webAppName
            + "/" + webAppRelURL);

    final HttpURLConnection httpCon = (HttpURLConnection) uri.toURL().openConnection();
    httpCon.connect();
    try {
        LOG.debug("HTTP GET: {}", uri);

        final int responseCode = httpCon.getResponseCode();

        final String content;
        if (responseCode == 200) {
            InputStream in = httpCon.getInputStream();
            try {
                content = IOUtils.toString(in, "UTF-8");
            } finally {
                in.close();
            }
        } else {
            content = null;
        }

        return new HTTPResponse(responseCode, httpCon.getResponseMessage(), content, uri);
    } finally {
        httpCon.disconnect();
    }
}

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

/**
 * Helper method used to actually send {@link WebThumb} request and check for common errors.
 * /*from   w w w. j  a v a2  s  .co m*/
 * @param webThumb the request to send
 * @return connection to extract the response from
 * @throws WebThumbException if any error occurs
 */
private HttpURLConnection sendWebThumb(WebThumb webThumb) throws WebThumbException {
    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("Request sent! Got response: " + responseCode + " " + connection.getResponseMessage());
            LOGGER.fine("Response content type: " + contentType);
            LOGGER.fine("Response content encoding: " + connection.getContentEncoding());
            LOGGER.fine("Response content length: " + connection.getContentLength());
        }

        if (responseCode == HttpURLConnection.HTTP_OK) {
            if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) {
                throw new WebThumbException(
                        "Server side error: " + IOUtils.toString(connection.getInputStream()));
            }
            if (!CONTENT_TYPE_TEXT_XML.equals(contentType)) {
                throw new WebThumbException("Unknown content type in response: " + contentType);
            }
            return connection;
        } 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.yahoo.sql4d.sql4ddriver.DDataSource.java

/**
 * For firing simple queries(i.e non join queries).
 * @param jsonQuery//  ww  w .j  a v a2 s.  c  om
 * @param print
 * @return 
 */
private Either<String, Either<Mapper4All, JSONArray>> fireQuery(String jsonQuery, boolean requiresMapping) {
    StringBuilder buff = new StringBuilder();
    try {
        URL url = null;
        try {
            url = new URL(String.format(brokerUrl, brokerHost, brokerPort));
        } catch (MalformedURLException ex) {
            Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
            return new Left<>("Bad Url : " + ex);
        }
        Proxy proxy = Proxy.NO_PROXY;
        if (proxyHost != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        }
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
        httpConnection.setRequestMethod("POST");
        httpConnection.addRequestProperty("content-type", "application/json");
        httpConnection.setDoOutput(true);
        httpConnection.getOutputStream().write(jsonQuery.getBytes());
        if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) {
            return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(),
                    httpConnection.getResponseMessage()));
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String line = null;
        while ((line = stdInput.readLine()) != null) {
            buff.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray possibleResArray = null;
    try {
        possibleResArray = new JSONArray(buff.toString());
    } catch (JSONException je) {
        return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString()));
    }
    if (requiresMapping) {
        return new Right<String, Either<Mapper4All, JSONArray>>(
                new Left<Mapper4All, JSONArray>(new Mapper4All(possibleResArray)));
    }
    return new Right<String, Either<Mapper4All, JSONArray>>(new Right<Mapper4All, JSONArray>(possibleResArray));
}

From source file:org.whispersystems.textsecure.internal.push.PushServiceSocket.java

private HttpURLConnection makeBaseRequest(String urlFragment, String method, String body)
        throws NonSuccessfulResponseCodeException, PushNetworkException {
    HttpURLConnection connection = getConnection(urlFragment, method, body);
    int responseCode;
    String responseMessage;/*from  ww w  . ja  v  a2  s .c  o m*/
    String response;

    try {
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    }

    switch (responseCode) {
    case 413:
        connection.disconnect();
        throw new RateLimitException("Rate limit exceeded: " + responseCode);
    case 401:
    case 403:
        connection.disconnect();
        throw new AuthorizationFailedException("Authorization failed!");
    case 404:
        connection.disconnect();
        throw new NotFoundException("Not found");
    case 409:
        MismatchedDevices mismatchedDevices;

        try {
            response = Util.readFully(connection.getErrorStream());
            mismatchedDevices = JsonUtil.fromJson(response, MismatchedDevices.class);
        } catch (JsonProcessingException e) {
            Log.w(TAG, e);
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new MismatchedDevicesException(mismatchedDevices);
    case 410:
        StaleDevices staleDevices;

        try {
            response = Util.readFully(connection.getErrorStream());
            staleDevices = JsonUtil.fromJson(response, StaleDevices.class);
        } catch (JsonProcessingException e) {
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new StaleDevicesException(staleDevices);
    case 411:
        DeviceLimit deviceLimit;

        try {
            response = Util.readFully(connection.getErrorStream());
            deviceLimit = JsonUtil.fromJson(response, DeviceLimit.class);
        } catch (JsonProcessingException e) {
            throw new NonSuccessfulResponseCodeException(
                    "Bad response: " + responseCode + " " + responseMessage);
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }

        throw new DeviceLimitExceededException(deviceLimit);
    case 417:
        throw new ExpectationFailedException();
    }

    if (responseCode != 200 && responseCode != 204) {
        throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
    }

    return connection;
}