Example usage for javax.net.ssl HttpsURLConnection setDoOutput

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

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:org.encuestame.core.util.SocialUtils.java

/**
 * Get Google Short Url./* w ww .j  a v a2s  . co m*/
 * @return
 */
public static String getGoGl(final String urlPath, String key) {
    log.debug("getGoGl url " + urlPath);
    log.debug("getGoGl key " + key);
    String shortUrl = null;
    URL simpleURL = null;
    HttpsURLConnection url = null;
    BufferedInputStream bStream = null;
    StringBuffer resultString = new StringBuffer("");
    String inputString = "{\"longUrl\":\"" + urlPath + "\"}";
    log.debug("getGoGl inputString " + inputString);
    try {
        simpleURL = new URL("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
        url = (HttpsURLConnection) simpleURL.openConnection();
        url.setDoOutput(true);
        url.setRequestProperty("content-type", "application/json");
        PrintWriter pw = new PrintWriter(url.getOutputStream());
        pw.print(inputString);
        pw.close();
    } catch (Exception ex) {
        log.error(ex);
        shortUrl = urlPath;
    }
    try {
        bStream = new BufferedInputStream(url.getInputStream());
        int i;
        while ((i = bStream.read()) >= 0) {
            resultString.append((char) i);
        }
        //  final Object jsonObject = JSONValue.parse(resultString.toString());
        //   final JSONObject o = (JSONObject) jsonObject;
        //   shortUrl = (String) o.get("id");
    } catch (Exception ex) {
        SocialUtils.log.error(ex);
        shortUrl = urlPath;
    }
    return shortUrl;
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {//from w  w w  .  j  av  a2  s.c  o m
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        localHttpsURLConnection.setRequestProperty("Content-Length",
                "" + Integer.toString(data.getBytes().length));
        localHttpsURLConnection.setRequestProperty("Content-Language", "en-US");

        localHttpsURLConnection.setUseCaches(false);
        localHttpsURLConnection.setDoInput(true);
        localHttpsURLConnection.setDoOutput(true);

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter.java

/**
 * Check if the response is valid//  ww w  .ja  va 2  s .  com
 * @param reCaptchaPrivateKey the ReCaptcha private key
 * @param reCaptchaPublicKey the ReCaptcha public key
 * @param gRecaptchaResponse the response
 * @return whether the user answered the ReCaptcha successfully
 */
public static boolean checkReCaptchaResponse(String reCaptchaPrivateKey, String reCaptchaPublicKey,
        String gRecaptchaResponse) {

    boolean isValid = false;

    //check if the public key is valid in case the admin entered it wrong
    boolean reCaptchaKeyValid = isReCaptchaKeyValid(reCaptchaPublicKey, reCaptchaPrivateKey);

    if (reCaptchaKeyValid && reCaptchaPrivateKey != null && reCaptchaPublicKey != null
            && gRecaptchaResponse != null && !gRecaptchaResponse.equals("")) {

        try {

            // the url to verify the response
            URL verifyURL = new URL("https://www.google.com/recaptcha/api/siteverify");
            HttpsURLConnection connection = (HttpsURLConnection) verifyURL.openConnection();
            connection.setRequestMethod("POST");

            // set the params
            String postParams = "secret=" + reCaptchaPrivateKey + "&response=" + gRecaptchaResponse;

            // make the request to verify if the user answered the ReCaptcha successfully
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(postParams);
            outputStream.flush();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            StringBuffer responseString = new StringBuffer();

            // read the response from the verify request
            while ((inputLine = bufferedReader.readLine()) != null) {
                responseString.append(inputLine);
            }

            bufferedReader.close();

            try {
                // create a JSON object from the response
                JSONObject responseObject = new JSONObject(responseString.toString());

                // get the value of the success field
                isValid = responseObject.getBoolean("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return isValid;
}

From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
        throws IOException, HttpResultException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);/*from   ww  w  .  ja va 2 s .c  o  m*/
    nection.setDoOutput(true);
    nection.setConnectTimeout(2000);
    nection.setReadTimeout(1000);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
        nection.setRequestProperty("Authorization", "token " + accessToken);
    }

    OutputStream os = nection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(params.toString());
    writer.flush();
    writer.close();
    os.close();

    try {

        nection.connect();

        int code = nection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) {
            throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage());
        }

        InputStream in = new BufferedInputStream(nection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            response.append(line);
        }

        try {
            return new JSONObject(response.toString());
        } catch (JSONException e) {
            throw new IOException(e);
        }

    } finally {
        nection.disconnect();
    }

}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName,
        String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;//from w ww .j  av a 2s  .c  o  m
        conn.setRequestProperty("Authorization", "Basic " + encode);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        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);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

private static HttpCookie getTmCookie(final String url, final String username, final String password,
        final int timeout) throws IOException {
    if (tmCookie != null && !tmCookie.hasExpired()) {
        return tmCookie;
    }// w  w  w  .  j  a v a 2s. c o m

    final String charset = UTF8_STR;
    final String query = String.format("u=%s&p=%s", URLEncoder.encode(username, charset),
            URLEncoder.encode(password, charset));
    final URLConnection connection = new URL(url).openConnection();

    if (!(connection instanceof HttpsURLConnection)) {
        return null;
    }

    final HttpsURLConnection http = (HttpsURLConnection) connection;

    http.setInstanceFollowRedirects(false);

    http.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });

    http.setRequestMethod("POST");
    http.setAllowUserInteraction(true);

    if (timeout != 0) {
        http.setConnectTimeout(timeout);
        http.setReadTimeout(timeout);
    }

    http.setDoOutput(true); // Triggers POST.
    http.setRequestProperty("Accept-Charset", charset);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    OutputStream output = null;

    try {
        output = http.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOGGER.debug(e, e);
            }
        }
    }

    LOGGER.info("fetching cookie: " + url);
    connection.connect();

    tmCookie = HttpCookie.parse(http.getHeaderField("Set-Cookie")).get(0);
    LOGGER.debug("cookie: " + tmCookie);

    return tmCookie;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in//  www  . jav a  2s .com
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}

From source file:Main.IrcBot.java

public static void postGit(String pasteBinSnippet, PrintWriter out) {
    try {//from www  .j  a va  2s .c o  m
        String url = "https://api.github.com/gists";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        JSONObject x = new JSONObject();
        JSONObject y = new JSONObject();
        JSONObject z = new JSONObject();
        z.put("content", pasteBinSnippet);
        y.put("index.txt", z);
        x.put("public", true);
        x.put("description", "LPBOT");
        x.put("files", y);
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "public=true&description=LPBOT";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(x.toString());
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        JSONObject gitResponse = new JSONObject(response.toString());
        String newGitUrl = gitResponse.getString("html_url");

        if (newGitUrl.length() > 0) {
            out.println("PRIVMSG #learnprogramming :The paste on Git: " + newGitUrl);
        }
        System.out.println(newGitUrl);
    } catch (Exception p) {

    }
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging out//from   w ww .  j  a  v  a 2 s  .c  o  m
 * 
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLogoutResponse(Context context)
        throws MalformedURLException, IOException, JSONException {
    // Refresh if necessary
    if (WebServiceAuthProvider.tokenExpiredHint(context)) {
        WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        URL url = new URL(urlForLogout(context));
        HttpsURLConnection connection = createSecureConnection(url);
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", authValue);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        try {
            LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (MalformedURLException e) {
            LoggingUtils.e(LOG_TAG,
                    "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                    null);
        } catch (IOException e) {
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*w  ww  .j  a va  2 s.com*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}