Example usage for javax.net.ssl HttpsURLConnection getOutputStream

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

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java

/**
 * ??http//from ww  w  .j av a2s. c om
 * 
 * @param context
 *            
 * @param requestURL
 *            ??
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-value??key???value???Stringbyte[]
 * @param photos
 *            key-value??? keyfilename
 *            value????InputStreambyte[]
 *            ?InputStreamopenUrl?
 * @return ?JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

    if (!httpMethod.equals("GET")) {
        Bundle dataparams = new Bundle();
        //         for (String key : params.keySet()) {
        //            if (params.getByteArray(key) != null) {
        //               dataparams.putByteArray(key, params.getByteArray(key));
        //            }
        //         }

        String BOUNDARY = KaixinUtil.md5(String.valueOf(System.currentTimeMillis())); // ?
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + BOUNDARY + endLine).getBytes());
        os.write((encodePostBody(params, BOUNDARY)).getBytes());
        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
            }
        }

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "?");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

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

/**
 * Post??web??,?utf-8/*from  w w  w.  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:hudson.plugins.pushover.PushoverApi.java

/**
 * Sends a raw bit of text via POST to PushoverApi.
 *
 * @param message//from  w  ww  . java 2s  .  c o  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.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java

private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception {
    /**//from w  w  w .  ja v  a2  s  .c o  m
     * A new connection to the endpoint that processes requests for refreshing the access token
     */
    HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL))
            .openConnection();
    refreshTokenConnection.setDoOutput(true);
    refreshTokenConnection.setRequestMethod("POST");
    refreshTokenConnection.setDoInput(true);
    refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE);
    refreshTokenConnection.connect();
    OutputStream refreshTokenRequestStream = null;
    try {
        refreshTokenRequestStream = refreshTokenConnection.getOutputStream();
        String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID,
                TOKEN_REFRESH_REDIRECT_URL, refreshToken);
        refreshTokenRequestStream.write(requestBody.getBytes());
        refreshTokenRequestStream.flush();
    } finally {
        if (refreshTokenRequestStream != null) {
            refreshTokenRequestStream.close();
        }
    }
    if (refreshTokenConnection.getResponseCode() == 200) {
        return parseRefreshTokenResponse(refreshTokenConnection);
    } else {
        throw new Exception("The attempt to refresh the access token failed");
    }
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {//from   w w  w.j  a  va2  s .c  o  m
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

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.c om
 * @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:org.openhab.binding.neato.internal.VendorVorwerk.java

@Override
public String executeRequest(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout) throws IOException {

    URL requestUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
    applyNucleoSslConfiguration(connection);
    connection.setRequestMethod(httpMethod);
    for (String propName : httpHeaders.stringPropertyNames()) {
        connection.addRequestProperty(propName, httpHeaders.getProperty(propName));
    }/* ww w. j  a  v a2s.  c o m*/
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    content.reset();
    IOUtils.copy(content, connection.getOutputStream());

    java.io.InputStream is = connection.getInputStream();
    return IOUtils.toString(is);
}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {//from w  ww .ja  va2  s  .co  m
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        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
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.qinder.api.APIGetter.java

protected HttpsURLConnection post(String sUrl, APIRequest request) {
    HttpsURLConnection urlConnection;
    URL url;/*  w w w  .j a va  2s .co m*/
    try {
        url = new URL(sUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        if (request.getPosts().size() != 0) {
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(request.getPosts());
            OutputStream post = urlConnection.getOutputStream();
            entity.writeTo(post);
            post.flush();
        }
        urlConnection.connect();
    } catch (IOException e) {
        urlConnection = null;
    }
    return urlConnection;
}

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 . j  a v  a  2 s . co  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;
}