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: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);/*from ww w  . j  a  v a  2 s.  c o m*/

    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());
}

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

/**
 * Synchronous call to get a new client credentials token, required for creating new account
 * /*from   www  . j a  va  2  s .  c om*/
 * @param url
 * @param clientCredentialsToken
 * @param httpMethod
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws JSONException
 */
public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken,
        String httpMethod, Bundle httpBody)
        throws MalformedURLException, IOException, ProtocolException, JSONException {
    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;
        }

        HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setRequestMethod(httpMethod);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        String authValue = "Bearer " + clientCredentialsToken;
        connection.setRequestProperty("Authorization", authValue);
        connection.connect();

        if (!httpBody.isEmpty()) {
            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 (FileNotFoundException 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.daoke.mobileserver.test.TestHttps.java

public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from www .  j av a2 s  .  co m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.voa.weixin.utils.HttpUtils.java

/**
 * httpspost?/*w ww  .j a v a2 s  .c o  m*/
 * 
 * @param url
 * @param param
 * @return
 * @throws Exception
 */
private static String doHttps(String url, String param, String method) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    byte[] content = param.getBytes("utf-8");
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), method, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
        } catch (Exception e) {
            throw e;
        }
        try {
            out = conn.getOutputStream();
            if (StringUtils.isNotBlank(param))
                out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from   w w w  .j  a  va 2s .  co m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

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;
    }//from   w w w  . ja 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.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;// w  w  w.  jav  a  2  s. c o m
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();
        urlConn.getOutputStream().write(postRequest);

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err
                        .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

/**
 * Validate the SafetyNet response using the Android Device Verification API. This API performs a validation check on
 * the JWS message returned from the SafetyNet service.
 *
 * <b>Important:</b> This use of the Android Device Verification API only validates that the provided JWS message was
 * received from the SafetyNet service. It <i>does not</i> verify that the payload data matches your original
 * compatibility check request./*from   w ww  .j a va2 s  . c o  m*/
 *
 * @param jws
 *     The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}.
 * @param apiKey
 *     The Android Device Verification API key
 * @return {@code true} if the provided JWS message was received from the SafetyNet service.
 * @throws SafetyNetError
 *     if an error occurs while verifying the JSON Web Signature.
 */
public static boolean validate(@NonNull String jws, @NonNull String apiKey) throws SafetyNetError {
    try {
        URL verifyApiUrl = new URL(GOOGLE_VERIFICATION_URL + apiKey);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] defaultTrustManagers = trustManagerFactory.getTrustManagers();
        TrustManager[] trustManagers = Arrays.copyOf(defaultTrustManagers, defaultTrustManagers.length + 1);
        trustManagers[defaultTrustManagers.length] = new GoogleApisTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);

        HttpsURLConnection urlConnection = (HttpsURLConnection) verifyApiUrl.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        JSONObject requestJson = new JSONObject();
        requestJson.put("signedAttestation", jws);
        byte[] outputInBytes = requestJson.toString().getBytes("UTF-8");
        OutputStream os = urlConnection.getOutputStream();
        os.write(outputInBytes);
        os.close();

        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        for (String line = reader.readLine(), nl = ""; line != null; line = reader.readLine(), nl = "\n") {
            sb.append(nl).append(line);
        }

        return new JSONObject(sb.toString()).getBoolean("isValidSignature");
    } catch (Exception e) {
        throw new SafetyNetError(e);
    }
}

From source file:org.sakaiproject.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;/*from   w  w w  . ja  va2s.  c  o m*/

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https/*  ww w.  j a  v a 2s.  c  o  m*/
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}