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:com.ct855.util.HttpsClientUtil.java

public static String getUrl(String url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setRequestProperty("Ocp-Apim-Subscription-Key", "d8400b4cdf104015bb23d7fe847352c8");
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);//from  w  w w. j  a v  a 2s  . com
    aConnection.setRequestMethod("GET");

    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

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

public static HttpsResponse getRequest(String Uri, String requestParameters) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;/*from   w w  w.j  a  va 2 s  . com*/
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        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) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static private HttpsURLConnection CreateConnection(URL url) throws IOException {
    System.setProperty("http.keepAlive", "false");

    HttpsURLConnection http = (HttpsURLConnection) url.openConnection();

    http.setConnectTimeout(30 * 1000);//from w ww .  jav  a  2 s. com
    http.setReadTimeout(30 * 1000);
    http.setUseCaches(false);
    http.setDoInput(true);
    http.setDoOutput(true);
    http.setUseCaches(false);

    return http;
}

From source file:no.digipost.android.api.ApiAccess.java

public static void uploadFile(Context context, String uri, File file) throws DigipostClientException {
    try {//from   w w  w  .  ja  v a 2s  .c  om
        try {

            FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM);
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName(ApiConstants.ENCODING));
            multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()),
                    ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING)));
            multipartEntity.addPart("file", filebody);
            multipartEntity.addPart("token", new StringBody(TokenStore.getAccess()));

            URL url = new URL(uri);
            HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection();
            httpsClient.setRequestMethod("POST");
            httpsClient.setDoOutput(true);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength());
            } else {
                httpsClient.setChunkedStreamingMode(0);
            }
            httpsClient.setRequestProperty("Connection", "Keep-Alive");
            httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + "");
            httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION,
                    ApiConstants.BEARER + TokenStore.getAccess());
            httpsClient.addRequestProperty(multipartEntity.getContentType().getName(),
                    multipartEntity.getContentType().getValue());

            try {
                OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream());
                multipartEntity.writeTo(outputStream);
                outputStream.flush();
                NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode());
            } finally {
                httpsClient.disconnect();
            }

        } catch (DigipostInvalidTokenException e) {
            OAuth.updateAccessTokenWithRefreshToken(context);
            uploadFile(context, uri, file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, context.getString(R.string.error_your_network));
        throw new DigipostClientException(context.getString(R.string.error_your_network));
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

public static JSONObject sendRequest(JSONObject request, String endpoint) {
    URL url;//from w  w w .j  av  a2s  .co  m
    try {
        url = new URL(authServer + "/" + endpoint);
    } catch (MalformedURLException e) {
        return null;
    }
    try {
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setReadTimeout(5000);
        con.setConnectTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.connect();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
        try {
            request.writeJSONString(writer);
            writer.flush();
            writer.close();

            if (con.getResponseCode() != 200) {
                return null;
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            try {
                JSONParser parser = new JSONParser();

                try {
                    return (JSONObject) parser.parse(reader);
                } catch (ParseException e) {
                    return null;
                }
            } finally {
                reader.close();
            }
        } finally {
            writer.close();
            con.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;/*from w  w w . j a  va 2  s  .  c o m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

static private String GetData(URL obj, String authToken) throws Exception {
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestProperty("X-Whistle-AuthToken", authToken);
    // System.out.println("Response Code : " + con.getResponseCode());
    if (con.getResponseCode() != 200) {
        logger.error("Failed to get requested data, response code: '{}'", con.getResponseCode());
        return null;
    }/*from w  ww .  j a v  a  2s  .  c om*/
    // Get the data
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    return response;
}

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

protected static String getAuthToken(String username, String password) throws Exception {
    logger.debug("Using username: '{}' / password: '{}'", username, password);

    URL obj = new URL(APIROOT + "tokens.json");
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestMethod("POST");
    String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username
            + "\",\"app_id\":\"com.whistle.WhistleApp\"}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);//from  w ww  .j  a  v  a  2s  . c o  m
    wr.flush();
    wr.close();
    if (con.getResponseCode() != 200) {
        logger.error("Username / password combination didn't work. Failed to get AuthenticationToken");
        return null;
    }
    // Read the buffer
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    // Parse the data and return the token
    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    return jobj.get("token").getAsString();
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * Post??web??,?utf-8//  w  ww  .  j  a v a2 s.c o  m
 * 
 * ?UTF8
 * 
 * @param actionUrl
 * @param params
 * @param timeout   
 * @return
 * @throws InvalidParameterException
 * @throws NetWorkException
 * @throws IOException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws Exception
 */
public static String post(String url, Map<String, String> params, int timeout)
        throws IOException, IllegalArgumentException, IllegalAccessException {
    if (url == null || url.equals(""))
        throw new IllegalArgumentException("url ");
    if (params == null)
        throw new IllegalArgumentException("params ?");
    if (url.indexOf('?') > 0) {
        url = url
                + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    } else {
        url = url
                + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    }

    String sb2 = "";
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    // try {
    URL uri = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection();
    // 
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    conn.setHostnameVerifier(HOSTNAME_VERIFIER);

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
        sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        sb.append(LINEND);
        sb.append(entry.getValue());
        sb.append(LINEND);
    }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(sb.toString().getBytes("UTF-8"));
    InputStream in = null;

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    if (res == 200) {
        in = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb2 = sb2 + line;
        }
    }
    outStream.close();
    conn.disconnect();
    return sb2;
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

private static String makePostApiCall(URL url, String content, String authToken) throws IOException {
    HttpsURLConnection conn = null;
    OutputStreamWriter writer = null;
    String res = "";
    try {//from   w  w  w . ja  v a 2  s  .c  o m
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(content);
        writer.close();

        if (conn.getResponseCode() / 100 >= 3) {
            Log.v("makePostApiCall", "Post content is: " + content);
            String error = "";
            try {
                JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                r.beginObject();
                while (r.hasNext()) {
                    error += r.nextName() + ": " + r.nextString() + "\r\n";
                }
                r.endObject();
                r.close();
            } catch (Throwable eex) {

            }
            Log.v("makePostApiCall", "Error string is: " + error);
            res = error;
            throw new IOException(
                    "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error);
        } else {
            JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream()));
            r.beginObject();
            while (r.hasNext()) {
                try {
                    res += r.nextName() + ": " + r.nextString() + "\n";
                } catch (Exception ex) {
                    r.skipValue();
                }
            }
            return res;
        }
    } finally {
        conn.disconnect();
        //return res;
    }
}