Example usage for javax.net.ssl HttpsURLConnection setUseCaches

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

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

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);//  ww w .j  a  v a2s .  c  om
    http.setReadTimeout(30 * 1000);
    http.setUseCaches(false);
    http.setDoInput(true);
    http.setDoOutput(true);
    http.setUseCaches(false);

    return http;
}

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

/**
 * Post??web??,?utf-8//from w  ww. j  a  v  a 2  s .com
 * 
 * ?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:ovh.tgrhavoc.aibot.RealmsUtil.java

private static String mcoapiGet(String address, YggdrasilSession session, ProxyData proxy) throws IOException {
    Proxy wrappedProxy = wrapProxy(proxy);
    HttpsURLConnection connection;
    if (wrappedProxy != null)
        connection = (HttpsURLConnection) new URL(address).openConnection(wrappedProxy);
    else/*from   w w  w.ja  v a 2 s  . c  om*/
        connection = (HttpsURLConnection) new URL(address).openConnection();

    connection.addRequestProperty("Cookie", "user=" + session.getUsername() + ";version=1.7.2;sid=token:"
            + session.getAccessToken().toString(16) + ":" + session.getSelectedProfile().getId());
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");

    connection.connect();

    InputStream in = connection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1)
        out.write(buffer, 0, read);

    return new String(out.toByteArray());
}

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

/**
 * ?Https// w  w w  .java 2 s  . c  om
 *
 * @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;
    }
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {//from w  ww . j  a va 2s. c om
        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:com.ds.kaixin.Util.java

/**
 * http//from w ww.j  a  v  a 2  s  .c o m
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueString
 *            byte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            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 = Util.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:com.kaixin.connect.Util.java

/**
 * http//w  w w . j  a v a2s  . c  o m
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueStringbyte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            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 = Util.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:cn.bidaround.ytcore.kaixin.KaixinUtil.java

/**
 * ??http//  w  ww  . j a  v  a2s.com
 * 
 * @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:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.//  w ww.  jav  a 2 s.c  om
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

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 .java  2 s. c  om
        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;
}