Java 类javax.net.ssl.HttpsURLConnection 实例源码

项目:HuskyUI-Plugin    文件:Metrics.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
项目:Leanplum-Android-SDK    文件:Util.java   
static HttpURLConnection createHttpUrlConnection(
    String fullPath, String httpMethod, boolean ssl, int timeoutSeconds)
    throws IOException {
  URL url = new URL(fullPath);
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  if (ssl) {
    SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ((HttpsURLConnection) urlConnection).setSSLSocketFactory(socketFactory);
  }
  urlConnection.setReadTimeout(timeoutSeconds * 1000);
  urlConnection.setConnectTimeout(timeoutSeconds * 1000);
  urlConnection.setRequestMethod(httpMethod);
  urlConnection.setDoOutput(!"GET".equals(httpMethod));
  urlConnection.setDoInput(true);
  urlConnection.setUseCaches(false);
  urlConnection.setInstanceFollowRedirects(true);
  Context context = Leanplum.getContext();
  urlConnection.setRequestProperty("User-Agent",
      getApplicationName(context) + "/" + getVersionName() + "/" + Request.appId() + "/" +
          Constants.CLIENT + "/" + Constants.LEANPLUM_VERSION + "/" + getSystemName() + "/" +
          getSystemVersion() + "/" + Constants.LEANPLUM_PACKAGE_IDENTIFIER);
  return urlConnection;
}
项目:RoughWorld    文件:WebClient.java   
public static void disableCertificateValidation() 
{
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] 
    { 
      new TrustAllManager() 
    };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new TrustAllHostnameVerifier();

    // Install the all-trusting trust manager
    try 
    {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
}
项目:Redunda-lib-java    文件:PingService.java   
/**
 * Pings the server
 * 
 * @source https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
 * */
private void execute() throws Throwable {
    //don't execute on debug-mode
    if(this.debugging == true)
        return;

    String url = "https://redunda.sobotics.org/status.json";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", UserAgent.getUserAgent());

    String parameters = "key="+this.apiKey;

    //add version parameter if available
    if (this.version != null)
        parameters = parameters+"&version="+this.version;

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

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

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

    String responseString = response.toString();

    //http://stackoverflow.com/a/15116323/4687348
    JsonParser jsonParser = new JsonParser();
    JsonObject object = (JsonObject)jsonParser.parse(responseString);

    try {
        boolean standbyResponse = object.get("should_standby").getAsBoolean();
        boolean oldValue = PingService.standby.get();
        PingService.standby.set(standbyResponse);

        String newLocation = object.get("location").getAsString();
        PingService.location = newLocation;

        if (standbyResponse != oldValue) {
            if (this.delegate != null)this.delegate.standbyStatusChanged(standbyResponse);
        }
    } catch (Throwable e) {
        //no apikey or server might be offline; don't change status!
        this.forwardError(e);
        throw e;
    }
}
项目:EMC    文件:WebUtils.java   
public static String get(String requestUrl, CookieManager cookies) throws Exception {
    URL url = new URL(urlEncode(requestUrl));
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    if (cookies != null)
        applyCookies(connection);

    connection.setConnectTimeout(8 * 1000);
    connection.setRequestProperty("User-Agent", FrameworkConstants.FRAMEWORK_NAME);
    connection.setRequestMethod("GET");

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String text;
    StringBuilder result = new StringBuilder();
    while ((text = in.readLine()) != null)
        result.append(text);

    in.close();

    storeCookies(connection);
    return result.toString();
}
项目:unionpay    文件:HttpClient.java   
/**
 * 创建连接
 *
 * @return
 * @throws ProtocolException
 */
private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException {
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        LogUtil.writeErrorLog(e.getMessage(), e);
        return null;
    }
    httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
    httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
    httpURLConnection.setUseCaches(false);// 取消缓存
    httpURLConnection.setRequestProperty("Content-type",
            "application/x-www-form-urlencoded;charset=" + encoding);
    httpURLConnection.setRequestMethod("GET");
    if ("https".equalsIgnoreCase(url.getProtocol())) {
        HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
        //是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false
        if(!SDKConfig.getConfig().isIfValidateRemoteCert()){
            husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
            husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况
        }
        return husn;
    }
    return httpURLConnection;
}
项目:bStats-Metrics    文件:MetricsLite.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
项目:jdk8u-jdk    文件:HttpsCreateSockTest.java   
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();

    URL url = new URL("https://localhost:" + address.getPort() + "/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    uc.setHostnameVerifier(new AllHostnameVerifier());
    if (uc instanceof javax.net.ssl.HttpsURLConnection) {
        ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory());
        System.out.println("Using TestSocketFactory");
    }
    uc.connect();
    System.out.println("CONNECTED " + uc);
    System.out.println(uc.getResponseMessage());
    uc.disconnect();
}
项目:JAVA-    文件:WeiXinKFUtils.java   
/**
 * 获取所有客服帐号
 *
 * @return
 */
public static String getAllKfAccount() {
    String token = WeiXinUtils.getToken();
    if (token != null) {
        String urlString = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + token;
        try {
            URL url = new URL(urlString);
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            httpsURLConnection.setDoInput(true);
            DataInputStream dataInputStream = new DataInputStream(httpsURLConnection.getInputStream());
            StringBuffer stringBuffer = new StringBuffer();
            int inputByte = dataInputStream.read();
            while (inputByte != -1) {
                stringBuffer.append((char) inputByte);
                inputByte = dataInputStream.read();
            }
            String kfString = stringBuffer.toString();
            return kfString;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return null;
}
项目:jarling    文件:HttpResponse.java   
public HttpResponse(HttpsURLConnection httpsURLConnection) throws StarlingBankRequestException {
    this.httpsURLConnection = httpsURLConnection;
    try {
        if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST){
            this.is = httpsURLConnection.getInputStream();
        }else {
            this.is = httpsURLConnection.getErrorStream();
            processStatusCode(httpsURLConnection);
        }
        this.statusCode = httpsURLConnection.getResponseCode();
        this.expiration = httpsURLConnection.getExpiration();
        this.request = httpsURLConnection.getURL();
        this.expiration = httpsURLConnection.getExpiration();
        this.lastModified = httpsURLConnection.getLastModified();
        this.responseHeaders = httpsURLConnection.getHeaderFields();
        this.contentType = httpsURLConnection.getContentType();
        this.contentEncoding = httpsURLConnection.getContentEncoding();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:classchecks    文件:Bmob.java   
/**
 * 初始化Bmob
 * 
 * @param appId 填写 Application ID
 * @param apiKey 填写 REST API Key
 * @param timeout 设置超时(1000~20000ms)
 * @return 注册结果
 */
public static boolean initBmob(String appId, String apiKey, int timeout) {
    APP_ID = appId;
    REST_API_KEY = apiKey;
    if (!APP_ID.equals(STRING_EMPTY) && !REST_API_KEY.equals(STRING_EMPTY)) {
        IS_INIT = true;
    }
    if (timeout > 1000 && timeout < 20000) {
        TIME_OUT = timeout;
    }
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        IS_INIT = false;
    }
    return isInit();
}
项目:openjdk-jdk10    文件:HttpsCreateSockTest.java   
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();

    URL url = new URL("https://localhost:" + address.getPort() + "/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    uc.setHostnameVerifier(new AllHostnameVerifier());
    if (uc instanceof javax.net.ssl.HttpsURLConnection) {
        ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory());
        System.out.println("Using TestSocketFactory");
    }
    uc.connect();
    System.out.println("CONNECTED " + uc);
    System.out.println(uc.getResponseMessage());
    uc.disconnect();
}
项目:cryptopia4j    文件:CryptopiaClient.java   
/**
 * Performs a raw public API query.
 * @param method the REST resource
 * @return result JSON
 */
private String publicApiQuery(String method) {
    BufferedReader in = null;
    try {
        final String urlMethod = String.format("%s/%s/%s", ROOT_URL, PRIVATE_PATH, method);
        final URLConnection con = new URL(urlMethod).openConnection();
        final HttpsURLConnection httpsConn = (HttpsURLConnection) con;
        httpsConn.setRequestMethod("GET");
        httpsConn.setInstanceFollowRedirects(true);
        con.setRequestProperty("Content-Type", "application/json");
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        final StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        return response.toString();
    } catch (Exception e) {
        throw new CryptopiaClientException("An error occurred communicating with Cryptopia.", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {}
        }
    }
}
项目:VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java    文件:HttpClient.java   
private String execute(HttpsURLConnection connection) throws IOException {
    int status = connection.getResponseCode();
    if (status == HTTP_OK) {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        connection.disconnect();
        return response.toString();
    } else {
        if (status == HTTP_NO_CONTENT) {
            throw new PublicAPIRequestRateLimitExceededException();
        } else if (status == HTTP_FORBIDDEN) {
            throw new ForbiddenException();
        } else {
            throw new RuntimeException();
        }
    }
}
项目:iBase4J-Common    文件:WeiXinCompanySendMsg.java   
/**
 * 重发
 * 
 * @param urlStr
 * @param parameters
 * @param count
 */
private static void reSend(String urlStr, String parameters, Map<String, Integer> count) throws IOException {
    if (count.get("times") == null) {
        count.put("times", 0);
    }
    int times = count.get("times");
    if (times < 5) {
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setReadTimeout(3000);
        conn.setConnectTimeout(3000);

        OutputStream output = conn.getOutputStream();
        output.write(parameters.getBytes("utf-8"));
        output.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String s = null;
        StringBuilder sb = new StringBuilder();
        while ((s = reader.readLine()) != null) {
            sb.append(s);
        }
        reader.close();
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String errcode = jsonObject.get("errcode").toString();
        if (!errcode.equals("0")) {
            count.put("times", count.get("times") + 1);
            reSend(urlStr, parameters, count);
        }
    }
}
项目:openjdk-jdk10    文件:HttpsSocketFacTest.java   
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();
    URL url = new URL("https://localhost:" + address.getPort() + "/test6614957/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    SimpleSSLSocketFactory sssf = new SimpleSSLSocketFactory();
    uc.setSSLSocketFactory(sssf);
    uc.setHostnameVerifier(new AllHostnameVerifier());
    InputStream is = uc.getInputStream();

    byte[] ba = new byte[1024];
    int read = 0;
    while ((read = is.read(ba)) != -1) {
        System.out.println(new String(ba, 0, read));
    }

    System.out.println("SimpleSSLSocketFactory.socketCreated = " + sssf.socketCreated);
    System.out.println("SimpleSSLSocketFactory.socketWrapped = " + sssf.socketWrapped);

    if (!sssf.socketCreated)
        throw new RuntimeException("Failed: Socket Factory not being called to create Socket");
}
项目:EmojiChat    文件:Metrics.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
项目:skLib    文件:Metrics.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
项目:VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java    文件:HttpsPost.java   
/**
 *
 * @param requestURL
 * @param entity
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpsPost(String requestURL, MultipartEntity entity) throws MalformedURLException, IOException {
    String boundary = "e2a540ab4e6c5ed79c01157c255a2b5007e157d7";
    URL url = new URL(requestURL);
    connection = (HttpsURLConnection) url.openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    process(entity, connection);
}
项目:boohee_v5.6    文件:OkHttpStack.java   
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
        this.mSslSocketFactory = sc.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (b.a.equals(url.getProtocol()) && this.mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(this.mSslSocketFactory);
    }
    return connection;
}
项目:GreenLightning    文件:SSLUtilities.java   
/**
 * Set the default X509 Trust Manager to an instance of a fake class that 
 * trust all certificates, even the self-signed ones. This method uses the 
 * old deprecated API from the com.sun.ssl package.
 *
 * @deprecated see {@link #_trustAllHttpsCertificates()}.
 */
private static void __trustAllHttpsCertificates() {
    com.sun.net.ssl.SSLContext context;

    // Create a trust manager that does not validate certificate chains
    if(__trustManagers == null) {
        __trustManagers = new com.sun.net.ssl.TrustManager[] 
            {new _FakeX509TrustManager()};
    } // if
    // Install the all-trusting trust manager
    try {
        context = com.sun.net.ssl.SSLContext.getInstance("SSL");
        context.init(null, __trustManagers, new SecureRandom());
    } catch(GeneralSecurityException gse) {
        throw new IllegalStateException(gse.getMessage());
    } // catch
    com.sun.net.ssl.HttpsURLConnection.
        setDefaultSSLSocketFactory(context.getSocketFactory());
}
项目:Codeforces    文件:HurlStack.java   
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception {
  server2.useHttps(sslClient.socketFactory, false);
  server2.enqueue(new MockResponse().setBody("This is secure HTTPS!"));

  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: " + server2.url("/").url())
      .setBody("This page has moved!"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .followSslRedirects(true)
      .build());
  connection = urlFactory.open(server.url("/").url());
  assertContent("This is secure HTTPS!", connection);
  assertFalse(connection instanceof HttpsURLConnection);
}
项目:app-ms    文件:VertxClientEngine.java   
public VertxClientEngine(final HttpClient httpClient) {

        try {
            this.httpClient = httpClient;
            sslContext = SSLContext.getDefault();
            hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        } catch (final NoSuchAlgorithmException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
项目:Vigilate    文件:Metrics.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
项目:GitHub    文件:JavaApiConverterTest.java   
@Test public void createJavaUrlConnection_https_extraHttpsMethods() throws Exception {
  Request okRequest = createArbitraryOkRequest().newBuilder()
      .get()
      .url("https://secure/request")
      .build();
  Handshake handshake = Handshake.get(TlsVersion.SSL_3_0, CipherSuite.TLS_RSA_WITH_NULL_MD5,
      Arrays.<Certificate>asList(SERVER_CERT), Arrays.<Certificate>asList(LOCAL_CERT));
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .handshake(handshake)
      .build();
  HttpsURLConnection httpsUrlConnection =
      (HttpsURLConnection) JavaApiConverter.createJavaUrlConnectionForCachePut(okResponse);

  assertEquals("SSL_RSA_WITH_NULL_MD5", httpsUrlConnection.getCipherSuite());
  assertEquals(SERVER_CERT.getSubjectX500Principal(), httpsUrlConnection.getPeerPrincipal());
  assertArrayEquals(new Certificate[] {LOCAL_CERT}, httpsUrlConnection.getLocalCertificates());
  assertArrayEquals(new Certificate[] {SERVER_CERT},
      httpsUrlConnection.getServerCertificates());
  assertEquals(LOCAL_CERT.getSubjectX500Principal(), httpsUrlConnection.getLocalPrincipal());
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void inspectHandshakeThroughoutRequestLifecycle() throws Exception {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse());

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .build());

  HttpsURLConnection httpsConnection
      = (HttpsURLConnection) urlFactory.open(server.url("/foo").url());

  // Prior to calling connect(), getting the cipher suite is forbidden.
  try {
    httpsConnection.getCipherSuite();
    fail();
  } catch (IllegalStateException expected) {
  }

  // Calling connect establishes a handshake...
  httpsConnection.connect();
  assertNotNull(httpsConnection.getCipherSuite());

  // ...which remains after we read the response body...
  assertContent("", httpsConnection);
  assertNotNull(httpsConnection.getCipherSuite());

  // ...and after we disconnect.
  httpsConnection.disconnect();
  assertNotNull(httpsConnection.getCipherSuite());
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception {
  server2.enqueue(new MockResponse().setBody("This is insecure HTTP!"));

  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: " + server2.url("/").url())
      .setBody("This page has moved!"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .followSslRedirects(true)
      .build());
  HttpsURLConnection connection = (HttpsURLConnection) urlFactory.open(server.url("/").url());
  assertContent("This is insecure HTTP!", connection);
  assertNull(connection.getCipherSuite());
  assertNull(connection.getLocalCertificates());
  assertNull(connection.getServerCertificates());
  assertNull(connection.getPeerPrincipal());
  assertNull(connection.getLocalPrincipal());
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception {
  server2.useHttps(sslClient.socketFactory, false);
  server2.enqueue(new MockResponse().setBody("This is secure HTTPS!"));

  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: " + server2.url("/").url())
      .setBody("This page has moved!"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .followSslRedirects(true)
      .build());
  connection = urlFactory.open(server.url("/").url());
  assertContent("This is secure HTTPS!", connection);
  assertFalse(connection instanceof HttpsURLConnection);
}
项目:IJPay    文件:HttpKit.java   
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    URL _url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty())
        for (Entry<String, String> entry : headers.entrySet())
            conn.setRequestProperty(entry.getKey(), entry.getValue());

    return conn;
}
项目:publicProject    文件:HurlStack.java   
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
项目:VBrowser-Android    文件:HttpRequestUtil.java   
public static void save2File(URLConnection urlConnection,String saveFilePath) throws IOException {

        DataInputStream dis = null;
        FileOutputStream fos = null;

        try {
            dis = new DataInputStream(urlConnection.getInputStream());
            //建立一个新的文件
            fos = new FileOutputStream(new File(saveFilePath));
            byte[] buffer = new byte[1024];
            int length;
            //开始填充数据
            while ((length = dis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        }finally {
            if(dis != null){
                dis.close();
            }
            if(fos != null){
                fos.close();
            }
            ((HttpsURLConnection)urlConnection).disconnect();
        }
    }
项目:gemnasium-maven-plugin    文件:PingMojo.java   
private void sendPing() throws MojoExecutionException {
    try {
        URL url = new URL(config.getApiBaseUrl() + "/ping");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String input;
        while ((input = br.readLine()) != null) {
            getLog().info(input);
        }

        br.close();

    } catch (Exception e) {
        throw new MojoExecutionException("Ping failed, please check network connection and configuration.", e);
    }
}
项目:AgentWorkbench    文件:SimpleOIDCClient.java   
/**
     * Retrieve provider metadata.
     * Provider configuration information
     * Obtaining the provider configuration information can be done either out-of-band or using the optional discovery process:
     *
     * @throws IOException Signals that an I/O exception has occurred.
     * @throws ParseException the parse exception
     * @throws KeyStoreException
     * @throws CertificateException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public void retrieveProviderMetadata() throws IOException, ParseException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException {

        URL providerConfigurationURL = issuerURI.resolve(URLPATH_WELL_KNOWN_OPENID).toURL();
//      System.out.println(providerConfigurationURL);
        URLConnection conn = providerConfigurationURL.openConnection();

        if (trustStoreFile != null) {
            Trust.trustSpecific((HttpsURLConnection) conn, trustStoreFile);
        }
        InputStream stream = conn.getInputStream();
        // Read all data from URL
        String providerInfo = null;
        try (java.util.Scanner s = new java.util.Scanner(stream)) {
            providerInfo = s.useDelimiter("\\A").hasNext() ? s.next() : "";
        }
        setProviderMetadata(OIDCProviderMetadata.parse(providerInfo));
    }
项目:JCurl    文件:JCurl.java   
private void processResponseCertificates(HttpURLConnection con, Response response) throws SSLPeerUnverifiedException {
  if (con instanceof HttpsURLConnection) {
    try {
      HttpsURLConnection secureConn = (HttpsURLConnection) con;
      response.cipherSuite = secureConn.getCipherSuite();
      response.serverCertificates = secureConn.getServerCertificates();
      response.clientCertificates = secureConn.getLocalCertificates();
    } catch (IllegalStateException e) {
      // If the response is not a 200, getting response certificates will fail with the (misleading) message
      // "connection not yet open". Ignore this.
    }
  }
}
项目:Redunda-lib-java    文件:DataService.java   
/**
 * Uploads a file to Redunda
 * 
 * This will ALWAYS overwrite the files on the server
 * 
 * @param filename The name of the file to upload
 * @throws IOException if the file couldn't be read
 * */
public void pushFile(String filename) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get(filename)));
    System.out.println(content);
    String encodedFilename;
    try {
        encodedFilename = URLEncoder.encode(this.encodeFilename(filename), "UTF-8");
    } catch (Throwable e) {
        e.printStackTrace();
        return;
    }


    String url = "https://redunda.sobotics.org/bots/data/"+encodedFilename+"?key="+this.apiKey;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", UserAgent.getUserAgent());

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

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

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
}
项目:hadoop-oss    文件:ReEncryptionClientProvider.java   
private HttpURLConnection configureConnection(HttpURLConnection conn)
    throws IOException {
  if (sslFactory != null) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  return conn;
}
项目:invest-stash-rest    文件:HttpRequests.java   
public T httpsPost(String jsonBody, Class<T> clazz) throws IOException {
URL url = new URL(HTTPS_PROTOCOL, ACCOUNT_KEY_SERVICE_HOST, HTTPS_PORT,
    ACCOUNT_KEY_ENDPOINT);
httpsConnection = (HttpsURLConnection) url.openConnection();
httpsConnection.setRequestMethod(HttpRequestMethod.POST.toString());
setConnectionParameters(httpsConnection, HttpRequestMethod.POST);

httpsConnection.setFixedLengthStreamingMode(jsonBody.getBytes().length);
try (OutputStreamWriter out = new OutputStreamWriter(
    httpsConnection.getOutputStream())) {
    out.write(jsonBody);
}
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(
    httpsConnection.getInputStream()))) {
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
    sb.append(inputLine);
    }
}
// setFieldNamingPolicy is used to here to convert from
// lower_case_with_underscore names retrieved from end point to camel
// case to match POJO class
Gson gson = new GsonBuilder().setFieldNamingPolicy(
    FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(sb.toString(), clazz);
   }
项目:EMC-Marketplace-Mod    文件:Web.java   
/**
 * Sends a POST request to a given url, with JSON data as payload
 * 
 * @param url
 * @param data
 * @return String
 */
public static String post(String uri, HashMap<String, String> payload) throws Exception {
    URL url = new URL(uri);
    Object connection = (uri.startsWith("https://") ? (HttpsURLConnection) url.openConnection()
            : (HttpURLConnection) url.openConnection());
    ((URLConnection) connection).setConnectTimeout(8 * 1000);
    ((URLConnection) connection).setRequestProperty("User-Agent", userAgent);

    ((URLConnection) connection).setDoInput(true);
    ((URLConnection) connection).setDoOutput(true);
    ((HttpURLConnection) connection).setRequestMethod("POST");
    ((URLConnection) connection).setRequestProperty("Accept", "application/json");
    ((URLConnection) connection).setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    OutputStreamWriter writer = new OutputStreamWriter(((URLConnection) connection).getOutputStream(), "UTF-8");
    writer.write(mapToJson(payload));
    writer.close();
    BufferedReader br = new BufferedReader(new InputStreamReader(((URLConnection) connection).getInputStream()));
    StringBuffer data = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        data.append(line);
    }
    br.close();
    ((HttpURLConnection) connection).disconnect();
    return data.toString();
}
项目:ServerConnect    文件:Metrics.java   
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}