Search in sources :

Example 86 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project ballerina by ballerina-lang.

the class HttpsClientRequest method doGet.

/**
 * Sends an HTTP GET request to a url.
 *
 * @param requestUrl - The URL of the service. (Example: "http://www.yahoo.com/search?params=value")
 * @param headers - http request header map
 * @return - HttpResponse from the end point
 * @throws IOException If an error occurs while sending the GET request
 */
public static HttpResponse doGet(String requestUrl, Map<String, String> headers, String serverHome) throws IOException {
    HttpsURLConnection conn = null;
    HttpResponse httpResponse;
    try {
        conn = getURLConnection(requestUrl, serverHome);
        // setting request headers
        for (Map.Entry<String, String> e : headers.entrySet()) {
            conn.setRequestProperty(e.getKey(), e.getValue());
        }
        conn.setRequestMethod(TestConstant.HTTP_METHOD_GET);
        conn.connect();
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
        } catch (IOException ex) {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        httpResponse.setHeaders(readHeaders(conn));
        httpResponse.setResponseMessage(conn.getResponseMessage());
        return httpResponse;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 87 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project ballerina by ballerina-lang.

the class HttpsClientRequest method getURLConnection.

private static HttpsURLConnection getURLConnection(String requestUrl, String serverHome) throws IOException {
    setSSlSystemProperties(serverHome);
    URL url = new URL(requestUrl);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setReadTimeout(30000);
    conn.setConnectTimeout(15000);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    return conn;
}
Also used : URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 88 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project nifi-minifi by apache.

the class HttpConnector method get.

public HttpURLConnection get(String endpointPath, Map<String, List<String>> headers) throws ConfigurationProviderException {
    String endpointUrl = baseUrl + endpointPath;
    if (logger.isDebugEnabled()) {
        logger.debug("Connecting to endpoint: " + endpointUrl);
    }
    URL url;
    try {
        url = new URL(endpointUrl);
    } catch (MalformedURLException e) {
        throw new ConfigurationProviderException("Malformed url " + endpointUrl, e);
    }
    HttpURLConnection httpURLConnection;
    try {
        if (proxy == null) {
            httpURLConnection = (HttpURLConnection) url.openConnection();
        } else {
            httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
        }
        if (sslContextFactory != null) {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
            SSLContext sslContext = sslContextFactory.getSslContext();
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            httpsURLConnection.setSSLSocketFactory(socketFactory);
        }
    } catch (IOException e) {
        throw new ConfigurationProviderException("Unable to connect to " + url, e);
    }
    if (proxyAuthorization != null) {
        httpURLConnection.setRequestProperty("Proxy-Authorization", proxyAuthorization);
    }
    headers.forEach((s, strings) -> httpURLConnection.setRequestProperty(s, strings.stream().collect(Collectors.joining(","))));
    return httpURLConnection;
}
Also used : ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 89 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project nifi-minifi by apache.

the class HttpsStatusCodeHealthCheck method getHttpURLConnection.

public static HttpURLConnection getHttpURLConnection(String url, SSLSocketFactory sslSocketFactory, String proxyHostname, int proxyPort) throws IOException {
    HttpsURLConnection httpURLConnection = (HttpsURLConnection) new URL(url).openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostname, proxyPort)));
    httpURLConnection.setSSLSocketFactory(sslSocketFactory);
    return httpURLConnection;
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URL(java.net.URL)

Example 90 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project MDM-Android-Agent by wso2-attic.

the class ServerUtilities method sendToServer.

public static Map<String, String> sendToServer(String epPostFix, Map<String, String> params, String option, Context context) throws IOException {
    String response = null;
    Map<String, String> response_params = new HashMap<String, String>();
    String endpoint = CommonUtilities.SERVER_URL + epPostFix;
    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    String ipSaved = mainPref.getString("ip", "");
    if (ipSaved != null && ipSaved != "") {
        endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT + CommonUtilities.SERVER_APP_ENDPOINT + epPostFix;
    }
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    HttpsURLConnection sConn = null;
    try {
        if (url.getProtocol().toLowerCase().equals("https")) {
            sConn = (HttpsURLConnection) url.openConnection();
            sConn = getTrustedConnection(context, sConn);
            sConn.setHostnameVerifier(WSO2MOBILE_HOST);
            conn = sConn;
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod(option);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Connection", "close");
        // post the request
        int status = 0;
        Log.v("Check verb", option);
        if (!option.equals("DELETE")) {
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            status = conn.getResponseCode();
            Log.v("Response Status", status + "");
            InputStream inStream = conn.getInputStream();
            response = inputStreamAsString(inStream);
            response_params.put("response", response);
            Log.v("Response Message", response);
            response_params.put("status", String.valueOf(status));
        } else {
            status = Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL);
        }
        if (status != Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL) && status != Integer.valueOf(CommonUtilities.REGISTERATION_SUCCESSFUL)) {
            throw new IOException("Post failed with error code " + status);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response_params;
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) SharedPreferences(android.content.SharedPreferences) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URL(java.net.URL) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.apache.http.ParseException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Entry(java.util.Map.Entry) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)522 URL (java.net.URL)310 IOException (java.io.IOException)177 HttpURLConnection (java.net.HttpURLConnection)128 InputStreamReader (java.io.InputStreamReader)93 InputStream (java.io.InputStream)89 Test (org.junit.Test)83 BufferedReader (java.io.BufferedReader)78 SSLContext (javax.net.ssl.SSLContext)70 OutputStream (java.io.OutputStream)54 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 MalformedURLException (java.net.MalformedURLException)48 URLConnection (java.net.URLConnection)47 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)46 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 HashMap (java.util.HashMap)34 DataOutputStream (java.io.DataOutputStream)32 KeyManagementException (java.security.KeyManagementException)32 JSONObject (org.json.JSONObject)29