javax.net.ssl.HttpsURLConnection Java Examples

The following examples show how to use javax.net.ssl.HttpsURLConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpsCreateSockTest.java    From jdk8u60 with GNU General Public License v2.0 8 votes vote down vote up
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();
}
 
Example #2
Source File: URLType.java    From webdsl with Apache License 2.0 7 votes vote down vote up
protected static void setAcceptAllVerifier(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {

        // Create the socket factory.
        // Reusing the same socket factory allows sockets to be
        // reused, supporting persistent connections.
        if( null == sslSocketFactory) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, ALL_TRUSTING_TRUST_MANAGER, new java.security.SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        }

        connection.setSSLSocketFactory(sslSocketFactory);

        // Since we may be using a cert with a different name, we need to ignore
        // the hostname as well.
        connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    }
 
Example #3
Source File: SslUtils.java    From AndroidWallet with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 * 
 * @param connection
 *           The connection to configure
 * @param serverThumbprint
 *           The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
   if (!(connection instanceof HttpsURLConnection)) {
      return;
   }

   HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

   if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
      httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
   }
   SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
   if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
      httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
   }
}
 
Example #4
Source File: HttpsCreateSockTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: CustomAction.java    From itracing2 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final String address = intent.getStringExtra(Devices.ADDRESS);
    final String source = intent.getStringExtra(Devices.SOURCE);
    final String action = Preferences.getCustomAction(context, address, source);

    if (action.startsWith("http://")) {
        new CallUrl<>(action, "address=" + address + "&source=" + source).start();
    }

    if (action.startsWith("https://")) {
        new CallUrl<HttpsURLConnection>(action, "address=" + address + "&source=" + source).start();
    }

    if (action.startsWith("mqtt://")) {
        new PublishMQTT(action, address + "," + source).start();
    }

    if (action.startsWith("tel:")) {
        new Phone(context, action).start();
    }

    if (!action.isEmpty()) {
        context.sendBroadcast(new Intent(action));
    }
}
 
Example #6
Source File: HurlStack.java    From FeedListViewDemo with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: HttpsCreateSockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: EclipseSWTTrustManager.java    From developer-studio with Apache License 2.0 6 votes vote down vote up
public static void initiate() {
	// if (initiated) return;
	SSLContext sc;
	try {
		TrustManager[] trustAllCerts = new TrustManager[] { new EclipseSWTTrustManager() };
		sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
	initiated = true;
}
 
Example #9
Source File: SslUtils.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 *
 * @param connection       The connection to configure
 * @param serverThumbprint The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
    if (!(connection instanceof HttpsURLConnection)) {
        return;
    }

    HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

    if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
        httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
    }
    SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
    if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
        // SSL socket factory is nonnull in Android Q
        httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
    }
}
 
Example #10
Source File: HurlStack.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: AuthenticatingHttpConnectorTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneIdentity_ResponseIsOk() throws Exception {

  final AgentProxy proxy = mock(AgentProxy.class);
  final Identity identity = mockIdentity();

  final AuthenticatingHttpConnector authConnector =
      createAuthenticatingConnector(Optional.of(proxy), ImmutableList.of(identity));

  final String path = "/another/one";

  final HttpsURLConnection connection = mock(HttpsURLConnection.class);
  when(connector.connect(argThat(matchesAnyEndpoint(path)),
      eq(method),
      eq(entity),
      eq(headers))
  ).thenReturn(connection);
  when(connection.getResponseCode()).thenReturn(200);

  final URI uri = new URI("https://helios" + path);

  authConnector.connect(uri, method, entity, headers);

  verify(connector).setExtraHttpsHandler(isA(HttpsHandler.class));
}
 
Example #12
Source File: LocationRetriever.java    From AppleWifiNlpBackend with Apache License 2.0 6 votes vote down vote up
public Collection<Location> retrieveLocations(String... macs) throws IOException {
    Request request = createRequest(macs);
    byte[] byteb = request.toByteArray();
    byte[] bytes = combineBytes(APPLE_MAGIC_BYTES, byteb, (byte) byteb.length);
    HttpsURLConnection connection = createConnection();
    prepareConnection(connection, bytes.length);
    OutputStream out = connection.getOutputStream();
    out.write(bytes);
    out.flush();
    out.close();
    InputStream in = connection.getInputStream();
    in.skip(10);
    Response response = wire.parseFrom(readStreamToEnd(in), Response.class);
    in.close();
    Collection<Location> locations = new ArrayList<Location>();
    for (Response.ResponseWifi wifi : response.wifis) {
        locations.add(fromResponseWifi(wifi));
    }
    return locations;
}
 
Example #13
Source File: HurlStack.java    From product-emm with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: OkHttpClient.java    From crosswalk-cordova-android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
 
Example #15
Source File: SslUtils.java    From bitshares_wallet with MIT License 6 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 * 
 * @param connection
 *           The connection to configure
 * @param serverThumbprint
 *           The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
   if (!(connection instanceof HttpsURLConnection)) {
      return;
   }

   HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

   if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
      httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
   }
   SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
   if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
      httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
   }
}
 
Example #16
Source File: HttpsSocketFacTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example #17
Source File: Engine.java    From acunetix-plugin with MIT License 5 votes vote down vote up
private HttpsURLConnection openConnection(String endpoint, String method, String contentType) throws IOException {
    URL url = new URL(endpoint);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    connection.addRequestProperty("X-AUTH", apiKey);
    return connection;
}
 
Example #18
Source File: CdnUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
public static void configHttps(HttpURLConnection conn) throws Exception {
    TrustManager[] tm = { new TrustAllX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

    sslContext.init(null, tm, new java.security.SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();

    // ssf.setHostnameVerifier(new TrustAllHostnameVerifier());
    ((HttpsURLConnection) conn).setSSLSocketFactory(ssf);
    ((HttpsURLConnection) conn)
            .setHostnameVerifier(new TrustAllHostnameVerifier());
}
 
Example #19
Source File: Fetcher.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected synchronized void openConnection(URL url)
    throws IOException {
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  if (sslShuffle) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  connection = conn;
}
 
Example #20
Source File: Fetcher.java    From big-c with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected synchronized void openConnection(URL url)
    throws IOException {
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  if (sslShuffle) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  connection = conn;
}
 
Example #21
Source File: Metrics2.java    From GriefPrevention with MIT License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param logger The used logger.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Logger logger, JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    if (logSentData) {
        logger.info("Sending data to bStats: {}", data.toString());
    }
    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();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        logger.info("Sent data to bStats and received response: {}", builder.toString());
    }
}
 
Example #22
Source File: CertificateChain.java    From Hands-On-Cryptography-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) throws MalformedURLException, IOException, CertificateNotYetValidException {
    URL url = new URL("https://www.packtpub.com");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.connect();
    Certificate[] certs = conn.getServerCertificates();

    Arrays.stream(certs).forEach(CertificateChain::printCert);

    System.out.println("There are " + certs.length + " certificates.");
    Arrays.stream(certs).map(cert -> (X509Certificate) cert)
            .forEach(x509 -> System.out.println(x509.getIssuerDN().getName()));
    System.out.println("The final certificate is for: " + conn.getPeerPrincipal());
}
 
Example #23
Source File: FileTransfer.java    From L.TileLayer.Cordova with MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example #24
Source File: SSLCertificateValidation.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void disable() {
    try {
        SSLContext sslc = SSLContext.getInstance("TLS");
        TrustManager[] trustManagerArray = { new NullX509TrustManager() };
        sslc.init(null, trustManagerArray, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: HttpClientTransport.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected boolean checkHTTPS(HttpURLConnection connection) {
    if (connection instanceof HttpsURLConnection) {

        // TODO The above property needs to be removed in future version as the semantics of this property are not preoperly defined.
        // One should use JAXWSProperties.HOSTNAME_VERIFIER to control the behavior

        // does the client want client hostname verification by the service
        String verificationProperty =
            (String) context.invocationProperties.get(HOSTNAME_VERIFICATION_PROPERTY);
        if (verificationProperty != null) {
            if (verificationProperty.equalsIgnoreCase("true")) {
                ((HttpsURLConnection) connection).setHostnameVerifier(new HttpClientVerifier());
            }
        }

        // Set application's HostNameVerifier for this connection
        HostnameVerifier verifier =
            (HostnameVerifier) context.invocationProperties.get(JAXWSProperties.HOSTNAME_VERIFIER);
        if (verifier != null) {
            ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
        }

        // Set application's SocketFactory for this connection
        SSLSocketFactory sslSocketFactory =
            (SSLSocketFactory) context.invocationProperties.get(JAXWSProperties.SSL_SOCKET_FACTORY);
        if (sslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        }

        return true;
    }
    return false;
}
 
Example #26
Source File: SankoGetGameDetailTask.java    From Hands-Chopping with Apache License 2.0 5 votes vote down vote up
@Override
protected String doInBackground(String... strings) {
    String[] parms=strings[0].split("&");
    String product_id=parms[0];
    String id=parms[1];
    StringBuilder builder = new StringBuilder();
    try {
        URL url=new URL("https://www.sonkwo.com/api/products/"+product_id+".json?locale=js&sonkwo_version=1&sonkwo_client=web&_="+String.valueOf(System.currentTimeMillis()));
        HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();

        httpsURLConnection.setRequestMethod("GET");
        httpsURLConnection.setRequestProperty("Accept","application/vnd.sonkwo.v5+json");
        httpsURLConnection.setRequestProperty("Accept-Encoding","deflate, br");
        httpsURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9,zh-TW;q=0.8");
        httpsURLConnection.setRequestProperty("Connection","keep-alive");
        httpsURLConnection.setRequestProperty("Host","www.sonkwo.com");
        httpsURLConnection.setRequestProperty("Referer","https://www.sonkwo.com/products/"+product_id+"?game_id="+id);
        httpsURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
        httpsURLConnection.setRequestProperty("X-Requested-With","XMLHttpRequest");
        //httpsURLConnection.setRequestProperty("Cookie","_sonkwo_community_session=eCKQrQ4i8%2BqTX1PhnNSXTxNN1sIjkSe%2BS3agPmJbTJHS9mY3h3gite8fCRlVVP%2F6a%2Fj8g0oYYQ8YdIggPihUqIJ5fH2%2Fdoi5yXfwhXit1r5V6dr4Jxso3OX30iMN7s3ma1PHmKpHR5howHL9lk4mWi9H2ncfEBXde6lcvHPJ2H0C6w%3D%3D--N%2BsFOFFVlHE%2FDVUp--rsjifub42VFgFk5fC2hoWg%3D%3D; Hm_lvt_4abede90a75b2ba39a03e7a40fcec65f="+timestamp+"; Hm_lpvt_4abede90a75b2ba39a03e7a40fcec65f="+timestamp);

        httpsURLConnection.connect();
        if(httpsURLConnection.getResponseCode()==200){
            InputStream inputStream = null;

            if (null == inputStream) {
                inputStream = httpsURLConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return builder.toString();
}
 
Example #27
Source File: TestSSLHttpServer.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private static String readOut(URL url) throws Exception {
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
  InputStream in = conn.getInputStream();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  IOUtils.copyBytes(in, out, 1024);
  return out.toString();
}
 
Example #28
Source File: Demo.java    From eLong-OpenAPI-JAVA-demo with Apache License 2.0 5 votes vote down vote up
private static void trustAllHttpsCertificates() throws Exception {  
    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
    javax.net.ssl.TrustManager tm = new miTM();  
    trustAllCerts[0] = tm;  
    javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
            .getInstance("SSL");  
    sc.init(null, trustAllCerts, null);  
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
            .getSocketFactory());  
}
 
Example #29
Source File: Webb.java    From DavidWebb with MIT License 5 votes vote down vote up
private void prepareSslConnection(HttpURLConnection connection) {
    if ((hostnameVerifier != null || sslSocketFactory != null) && connection instanceof HttpsURLConnection) {
        HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
        if (hostnameVerifier != null) {
            sslConnection.setHostnameVerifier(hostnameVerifier);
        }
        if (sslSocketFactory != null) {
            sslConnection.setSSLSocketFactory(sslSocketFactory);
        }
    }
}
 
Example #30
Source File: Engine.java    From acunetix-plugin with MIT License 5 votes vote down vote up
private Resp doGet(String urlStr) throws IOException {
    HttpsURLConnection connection = openConnection(urlStr);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
        String inputLine;
        StringBuilder resbuf = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            resbuf.append(inputLine);
        }
        Resp resp = new Resp();
        resp.respCode = connection.getResponseCode();
        resp.jso = JSONObject.fromObject(resbuf.toString());
        return resp;
    }
}