Example usage for javax.net.ssl HttpsURLConnection getResponseMessage

List of usage examples for javax.net.ssl HttpsURLConnection getResponseMessage

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static boolean sendCommand(Configuration conf, String path) throws IOException {
    setupSslProps(conf);//from ww w.  j  a  va 2s .com
    int sslPort = getSslAddr(conf).getPort();
    int err = 0;
    StringBuilder b = new StringBuilder();

    HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), "");
    Set<String> hostsList = hostsReader.getHosts();
    for (String hostname : hostsList) {
        HttpsURLConnection connection = null;
        try {
            connection = openConnection(hostname, sslPort, path);
            connection.connect();
            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates();
                if (clientCerts != null) {
                    for (X509Certificate cert : clientCerts)
                        sb.append("\n Client certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No client certificates were found");
                }
                X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
                if (serverCerts != null) {
                    for (X509Certificate cert : serverCerts)
                        sb.append("\n Server certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No server certificates were found");
                }
                LOG.debug(sb.toString());
            }
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
                err++;
            }
        } catch (IOException e) {
            b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
            if (LOG.isDebugEnabled())
                LOG.debug("Exception happend for host " + hostname, e);
            err++;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
    if (err > 0) {
        System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:")
                + b.toString() + "\n");
        return false;
    }
    return true;
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public String callQueryFacility(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    // Setup connection
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  w w  w .java  2s .c  o m
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);//from   w w w . j ava  2  s  . c om
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:com.wso2telco.MePinStatusRequest.java

public String call() {
    String allowStatus = null;//w ww  .ja  v  a 2  s. co m

    String clientId = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinClientId();
    String url = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinUrl();
    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + "";
    if (log.isDebugEnabled()) {
        log.info("MePIN Status URL : " + url);
    }
    String authHeader = "Basic " + configurationService.getDataHolder().getMobileConnectConfig()
            .getSessionUpdaterConfig().getMePinAccessToken();

    try {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", authHeader);

        String resp = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            resp += output;
        }
        br.close();

        if (log.isDebugEnabled()) {
            log.debug("MePIN Status Response Code : " + statusCode + " " + connection.getResponseMessage());
            log.debug("MePIN Status Response : " + resp);
        }

        JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject();
        String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString();
        JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow");

        if (allowObject != null) {
            allowStatus = allowObject.getAsString();
            if (Boolean.parseBoolean(allowStatus)) {
                allowStatus = "APPROVED";
                String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId);
                DatabaseUtils.updateStatus(sessionID, allowStatus);
            }
        }

    } catch (IOException e) {
        log.error("Error while MePIN Status request" + e);
    } catch (SQLException e) {
        log.error("Error in connecting to DB" + e);
    }
    return allowStatus;
}

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

private void uploadExternalFile(String method, String url, byte[] data) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);//  w w w.ja v a2s . co  m
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.connect();

    try {
        OutputStream out = connection.getOutputStream();
        out.write(data);
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

/**
 * ??HTTPS GET/* ww w . j a v a 2 s  .c  o m*/
 * 
 * @param url URL
 * @return 
 */
public static HttpResp doHttpsGet(URL url) {

    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    Reader reader = null;

    try {
        // ???httphttps
        String protocol = url.getProtocol();
        if (!PROTOCOL_HTTPS.equals(protocol)) {
            throw new XinException("xin.error.url", "?https");
        }

        // 
        conn = (HttpsURLConnection) url.openConnection();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, tmArr, new SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        // ?
        conn.setConnectTimeout(connTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        // UserAgent
        conn.setRequestProperty("User-Agent", "java-sdk");

        // ?
        conn.connect();

        // ?
        inputStream = conn.getInputStream();
        reader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            stringBuilder.append(inputLine);
            stringBuilder.append("\n");
        }

        // 
        HttpResp resp = new HttpResp();
        resp.setStatusCode(conn.getResponseCode());
        resp.setStatusPhrase(conn.getResponseMessage());
        resp.setContent(stringBuilder.toString());

        // 
        return resp;
    } catch (MalformedURLException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (IOException e) {
        throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage()));
    } catch (KeyManagementException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (NoSuchAlgorithmException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } finally {

        if (reader != null) {
            try {
                reader.close();

            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", reader");
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", ?");
            }
        }

        // 
        quietClose(conn);
    }
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /*  w w w. ja v a2  s  . co m*/
 * @param strURL ?URL
 * @return jsonStr JSON??
 */
protected String sendHttpRequest(final String strURL) {
    String jsonStr = "";
    try {
        URL url = new URL(strURL);
        /*---------make and set HTTP header-------*/
        //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection();
        HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection());

        /*---------show HTTP header information-------*/
        System.out.println("\n ---------http header---------- ");
        Map headers = con.getHeaderFields();
        for (Object key : headers.keySet()) {
            System.out.println(key + ": " + headers.get(key));
        }
        con.connect();

        /*---------get HTTP body information---------*/
        String contentType = con.getHeaderField("Content-Type");
        //String charSet = "Shift-JIS";// "ISO-8859-1";
        String charSet = "UTF-8";// "ISO-8859-1";
        for (String elm : contentType.replace(" ", "").split(";")) {
            if (elm.startsWith("charset=")) {
                charSet = elm.substring(8);
                break;
            }
        }

        /*---------show HTTP body information----------*/
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet));
        } catch (Exception e_) {
            System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
            br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet));
        }
        System.out.println("\n ---------show HTTP body information----------");
        String line = "";
        while ((line = br.readLine()) != null) {
            jsonStr += line;
        }
        br.close();
        con.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(jsonStr);
    return jsonStr;
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *//*from  w  ww. j a  v  a2s.c o m*/
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language/*from w ww.  j a v  a 2 s. c om*/
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

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

private void uploadAttachment(String method, String url, InputStream data, long dataSize, byte[] key,
        ProgressListener listener) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);/*from   w ww. ja va  2 s . c  o  m*/

    if (dataSize > 0) {
        connection
                .setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize));
    } else {
        connection.setChunkedStreamingMode(0);
    }

    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Connection", "close");
    connection.connect();

    try {
        OutputStream stream = connection.getOutputStream();
        AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream);
        byte[] buffer = new byte[4096];
        int read, written = 0;

        while ((read = data.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            written += read;

            if (listener != null) {
                listener.onAttachmentProgress(dataSize, written);
            }
        }

        data.close();
        out.flush();
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}