Example usage for javax.net.ssl HttpsURLConnection setDoInput

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

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {// w  w  w .  ja  va2 s .c  om
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java

/**
 * Send REST call/*from  w  ww .java 2  s . c  om*/
 */
public boolean sendRESTCall(String url, String urlParameters) throws IOException {
    HttpsURLConnection connection = null;
    try {
        URL smsProviderUrl = new URL(url + urlParameters);
        connection = (HttpsURLConnection) smsProviderUrl.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(SMSOTPConstants.HTTP_METHOD);
        if (connection.getResponseCode() == 200) {
            if (log.isDebugEnabled()) {
                log.debug("Code is successfully sent to your mobile number");
            }
            return true;
        }
        connection.disconnect();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.error("Invalid URL", e);
        }
        throw new MalformedURLException();
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while setting the HTTP method", e);
        }
        throw new ProtocolException();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while getting the HTTP response", e);
        }
        throw new IOException();
    } finally {
        connection.disconnect();
    }
    return false;
}

From source file:hudson.plugins.pushover.PushoverApi.java

/**
 * Sends a raw bit of text via POST to PushoverApi.
 *
 * @param message/* w w w. j  a v a2 s .co m*/
 * @return JSON reply from PushoverApi.
 * @throws IOException
 */
private String sendToPushover(String message) throws IOException {
    URL pushoverUrl = new URL(PUSHOVER_URL);
    HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(pushoverUrl);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        outputStream.write(message.getBytes(Charset.forName("UTF-8")));
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    StringBuffer ret = new StringBuffer();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            ret.append(inputLine);
    } finally {
        in.close();
    }
    return ret.toString();
}

From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java

protected void registerWithBackend() {

    final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE);

    Thread httpThread = new Thread(new Runnable() {

        private String TAG = "httpThread";
        private String ENDPOINT = "https://otp.demo.ownpush.com/push/register";

        @Override// w  w w.j  a va  2  s . c o m
        public void run() {
            URL urlObj;

            try {
                urlObj = new URL(ENDPOINT);

                String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null);

                if (install_id == null) {
                    return;
                }

                String mPostData = "push_id=" + install_id;
                HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();

                con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                con.setRequestProperty("Accept", "*/*");
                con.setDoInput(true);
                con.setRequestMethod("POST");
                con.getOutputStream().write(mPostData.getBytes());
                con.connect();
                int http_status = con.getResponseCode();

                if (http_status != 200) {
                    Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status);
                    return;
                }

                InputStream stream;
                stream = con.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                String data = sb.toString();

                if (data.contains("device_uid")) {
                    JSONObject json = new JSONObject(data);
                    String device_id = json.getString("device_uid");
                    pref.edit().putString("device_uid", device_id).commit();
                    Log.d(TAG, "GOT DEVICE UID OF " + device_id);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateUI();
                        }
                    });

                }

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

    httpThread.start();
}

From source file:com.omertron.pushoverapi.PushoverApi.java

/**
 * Sends a raw bit of text via POST to PushoverApi.
 *
 * @param message//from w ww  .  j a  va  2 s  .co m
 * @return JSON reply from PushoverApi.
 * @throws IOException
 */
private String sendToPushover(String message) throws IOException {
    URL pushoverUrl = new URL(PUSHOVER_URL);

    if (isDebug)
        System.out.println("Pushing with URL: " + message);

    HttpsURLConnection connection = (HttpsURLConnection) pushoverUrl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        outputStream.write(message.getBytes(Charset.forName("UTF-8")));
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    InputStreamReader isr = null;
    BufferedReader br = null;
    StringBuilder output = new StringBuilder();
    try {
        isr = new InputStreamReader(connection.getInputStream());
        br = new BufferedReader(isr);
        connection.disconnect();

        String outputCache;
        while ((outputCache = br.readLine()) != null) {
            output.append(outputCache);
        }
    } finally {
        if (isr != null) {
            isr.close();
        }
        if (br != null) {
            br.close();
        }
    }
    return output.toString();
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendGetRequest(String endpoint, String urlParameters) throws IOException {
    // build connection object for GET request
    URL obj = new URL(endpoint + urlParameters);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(false);//from w  w  w . j  a  v a  2 s . co  m
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestMethod("GET");
    return conn;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code HttpsURLConnection} from the given
 * {@code context} and {@code hostnameVerifier}.
 * /*ww w. jav a  2  s .c  o m*/
 * @param context
 *            the TrustManagerFactory to get the SSLContext
 * @return the new {@code HttpsURLConnection} instance.
 * @throws IOException
 *             if an error occurs while opening the connection.
 */
private HttpsURLConnection getURLConnection(SSLContext context, HostnameVerifier hostnameVerifier)
        throws IOException {

    URL url = new URL("https://10.0.2.2/mycode/digitalSig.php");

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setConnectTimeout(3000);
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setHostnameVerifier(hostnameVerifier);

    return urlConnection;
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException {
    // build conn object for POST request
    URL obj = new URL(endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from   w w  w  . j a  va2  s .co m
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params);
    wr.flush();
    wr.close();
    return conn;
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from  w  ww.ja v a2 s  . c o  m
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {//from w w w  .  j a  v a2s.co m
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}