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:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Check if specified dataset already exists on server
 * /*from ww w.  j  a v  a2  s.c o  m*/
 * @param dataSetName
 * @return boolean true if the dataset already exits, false if not
 * @throws IOException
 * @throws HttpException
 */
public static boolean chechIfExist(String dataSetName) throws IOException, HttpException {
    boolean exists = false;
    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("GET");

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

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

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

/**
 * Delete specified dataset/*ww w .j a v a  2  s  . c  o  m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void deleteDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("delete dataset: " + dataSetName);

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

    // 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:cc.vileda.sipgatesync.api.SipgateApi.java

@NonNull
private static String getUrl(final String apiUrl, final String token) throws IOException {
    final HttpURLConnection urlConnection = getConnection(apiUrl);
    urlConnection.setDoInput(true);/*from w w w  .  j a va2  s  . c  o m*/
    urlConnection.setRequestMethod("GET");
    if (token != null) {
        urlConnection.setRequestProperty("Authorization", "Bearer " + token);
    }
    StringBuilder sb = new StringBuilder();
    int HttpResult = urlConnection.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();

        return sb.toString();
    } else {
        System.out.println(urlConnection.getResponseMessage());
    }

    return "";
}

From source file:Main.java

protected static String getResponseAsString(HttpURLConnection conn, boolean responseError) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    String header = conn.getHeaderField("Content-Encoding");
    boolean isGzip = false;
    if (header != null && header.toLowerCase().contains("gzip")) {
        isGzip = true;//from  ww  w.j a  va 2 s . c  om
    }
    InputStream es = conn.getErrorStream();
    if (es == null) {
        InputStream input = conn.getInputStream();
        if (isGzip) {
            input = new GZIPInputStream(input);
        }
        return getStreamAsString(input, charset);
    } else {
        if (isGzip) {
            es = new GZIPInputStream(es);
        }
        String msg = getStreamAsString(es, charset);
        if (TextUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else if (responseError) {
            return msg;
        } else {
            throw new IOException(msg);
        }
    }
}

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);/*from www  . ja  va 2  s . com*/
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    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 + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:org.asqatasun.websnapshot.urlmanager.utils.UrlUtils.java

/**
 *
 * @param targetUrl/*  w w w . ja  v a 2s .c o  m*/
 * @return
 */
public static String checkURLAvailable(String targetUrl) {
    try {
        URL url = new URL(targetUrl);
        URLConnection urlConnection = url.openConnection();

        HttpURLConnection.setFollowRedirects(true);
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setRequestMethod("HEAD");

        if (httpURLConnection.getResponseCode() >= MIN_HTTP_VALID_CODE
                && httpURLConnection.getResponseCode() < MAX_HTTP_VALID_CODE) {
            return URL_AVAILABLE;
        }
        urlConnection = url.openConnection();
        httpURLConnection.disconnect();
        HttpURLConnection.setFollowRedirects(true);
        httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setRequestMethod("GET");

        if (httpURLConnection.getResponseCode() >= MIN_HTTP_VALID_CODE
                && httpURLConnection.getResponseCode() < MAX_HTTP_VALID_CODE) {
            return URL_AVAILABLE;
        } else {
            return Integer.toString(httpURLConnection.getResponseCode()) + " "
                    + httpURLConnection.getResponseMessage();
        }
    } catch (Exception e) {
        return URL_NOT_AVAILABLE;
    }
}

From source file:de.ipbhalle.metfrag.pubchem.PubChemWebService.java

/**
 * //from  w  ww  .ja  v  a2  s.co m
 * @author c-ruttkies
 * 
 * @param urlname
 * @return
 */
private static InputStream getInputStreamFromURL(String urlname) {
    InputStream stream = null;

    try {
        URL url = new URL(urlname);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }
        stream = conn.getInputStream();
    } catch (MalformedURLException mue) {
        System.err.println("Error: Could create URL object!");
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Error: Could not open URL connection!");
        System.exit(2);
    }

    return stream;
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() {
    Map<String, DiagnosticsStatus> statuses = new HashMap<>();

    for (String tspUrl : ServerConf.getTspUrl()) {
        try {//from w w  w  . j a  v  a  2 s. co m
            URL url = new URL(tspUrl);

            log.info("Checking timestamp server status for url {}", url);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS);
            con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/timestamp-query");
            con.connect();

            log.info("Checking timestamp server con {}", con);

            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok",
                        con.getResponseCode(), con.getResponseMessage());
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            } else {
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            }

        } catch (Exception e) {
            log.warn("Timestamp status check failed {}", e);

            statuses.put(tspUrl,
                    new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl));
        }
    }
    return statuses;

}

From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java

private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);/*from   w ww. jav a 2s.  c o m*/
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }

    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

From source file:com.binil.pushnotification.ServerUtil.java

/**
 * Issue a POST request to the server./*from   www. j a  v a  2  s.  co  m*/
 *
 * @param endpoint POST address.
 * @param params   request parameters.
 * @throws java.io.IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException {

    URL url = new URL(endpoint);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
    urlConnection.setRequestProperty("Accept", "*/*");

    urlConnection.setDoOutput(true);

    JSONObject json = new JSONObject(params);
    String body = json.toString();
    urlConnection.setFixedLengthStreamingMode(body.length());

    try {
        OutputStream os = urlConnection.getOutputStream();
        os.write(body.getBytes("UTF-8"));
        os.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        int status = urlConnection.getResponseCode();
        String connectionMsg = urlConnection.getResponseMessage();
        urlConnection.disconnect();

        if (status != HttpURLConnection.HTTP_OK) {
            Log.wtf(TAG, connectionMsg);
            throw new IOException("Post failed with error code " + status);
        }
    }

}