Java Code Examples for javax.net.ssl.HttpsURLConnection

The following are top voted examples for showing how to use javax.net.ssl.HttpsURLConnection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: HuskyUI-Plugin   File: Metrics.java   Source Code and License 11 votes vote down vote up
/**
 * 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 :)
}
 
Example 2
Project: Leanplum-Android-SDK   File: Util.java   Source Code and License 8 votes vote down vote up
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;
}
 
Example 3
Project: Redunda-lib-java   File: PingService.java   Source Code and License 8 votes vote down vote up
/**
 * 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;
	}
}
 
Example 4
Project: EMC   File: WebUtils.java   Source Code and License 8 votes vote down vote up
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();
}
 
Example 5
Project: bStats-Metrics   File: MetricsLite.java   Source Code and License 7 votes vote down vote up
/**
 * 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 :)
}
 
Example 6
Project: JAVA-   File: WeiXinKFUtils.java   Source Code and License 7 votes vote down vote up
/**
 * 获取所有客服帐号
 *
 * @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;
}
 
Example 7
Project: jarling   File: HttpResponse.java   Source Code and License 7 votes vote down vote up
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();
    }
}
 
Example 8
Project: classchecks   File: Bmob.java   Source Code and License 7 votes vote down vote up
/**
 * 初始化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();
}
 
Example 9
Project: unionpay   File: HttpClient.java   Source Code and License 7 votes vote down vote up
/**
 * 创建连接
 *
 * @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;
}
 
Example 10
Project: openjdk-jdk10   File: HttpsCreateSockTest.java   Source Code and License 7 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 11
Project: cryptopia4j   File: CryptopiaClient.java   Source Code and License 7 votes vote down vote up
/**
 * 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) {}
        }
    }
}
 
Example 12
Project: VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java   File: HttpClient.java   Source Code and License 7 votes vote down vote up
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();
        }
    }
}
 
Example 13
Project: iBase4J-Common   File: WeiXinCompanySendMsg.java   Source Code and License 7 votes vote down vote up
/**
 * 重发
 * 
 * @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);
		}
	}
}
 
Example 14
Project: openjdk-jdk10   File: HttpsSocketFacTest.java   Source Code and License 7 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 15
Project: EmojiChat   File: Metrics.java   Source Code and License 6 votes vote down vote up
/**
 * 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 :)
}
 
Example 16
Project: GitHub   File: BasePresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void handleApiError(ANError error) {

    if (error == null || error.getErrorBody() == null) {
        getMvpView().onError(R.string.api_default_error);
        return;
    }

    if (error.getErrorCode() == AppConstants.API_STATUS_CODE_LOCAL_ERROR
            && error.getErrorDetail().equals(ANConstants.CONNECTION_ERROR)) {
        getMvpView().onError(R.string.connection_error);
        return;
    }

    if (error.getErrorCode() == AppConstants.API_STATUS_CODE_LOCAL_ERROR
            && error.getErrorDetail().equals(ANConstants.REQUEST_CANCELLED_ERROR)) {
        getMvpView().onError(R.string.api_retry_error);
        return;
    }

    final GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation();
    final Gson gson = builder.create();

    try {
        ApiError apiError = gson.fromJson(error.getErrorBody(), ApiError.class);

        if (apiError == null || apiError.getMessage() == null) {
            getMvpView().onError(R.string.api_default_error);
            return;
        }

        switch (error.getErrorCode()) {
            case HttpsURLConnection.HTTP_UNAUTHORIZED:
            case HttpsURLConnection.HTTP_FORBIDDEN:
                setUserAsLoggedOut();
                getMvpView().openActivityOnTokenExpire();
            case HttpsURLConnection.HTTP_INTERNAL_ERROR:
            case HttpsURLConnection.HTTP_NOT_FOUND:
            default:
                getMvpView().onError(apiError.getMessage());
        }
    } catch (JsonSyntaxException | NullPointerException e) {
        Log.e(TAG, "handleApiError", e);
        getMvpView().onError(R.string.api_default_error);
    }
}
 
Example 17
Project: skLib   File: Metrics.java   Source Code and License 6 votes vote down vote up
/**
 * 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 :)
}
 
Example 18
Project: VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java   File: HttpsPost.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @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);
}
 
Example 19
Project: boohee_v5.6   File: OkHttpStack.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 20
Project: GreenLightning   File: SSLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 21
Project: Codeforces   File: HurlStack.java   Source Code and 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 22
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 23
Project: jdk8u-jdk   File: HttpsCreateSockTest.java   Source Code and License 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 24
Project: app-ms   File: VertxClientEngine.java   Source Code and License 6 votes vote down vote up
public VertxClientEngine(final HttpClient httpClient) {

        try {
            this.httpClient = httpClient;
            sslContext = SSLContext.getDefault();
            hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        } catch (final NoSuchAlgorithmException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
 
Example 25
Project: Vigilate   File: Metrics.java   Source Code and License 6 votes vote down vote up
/**
 * 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 :)
}
 
Example 26
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 27
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 28
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 29
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 30
Project: IJPay   File: HttpKit.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 31
Project: publicProject   File: HurlStack.java   Source Code and 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 32
Project: VBrowser-Android   File: HttpRequestUtil.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
 
Example 33
Project: gemnasium-maven-plugin   File: PingMojo.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 34
Project: AgentWorkbench   File: SimpleOIDCClient.java   Source Code and License 6 votes vote down vote up
/**
	 * 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));
	}
 
Example 35
Project: JCurl   File: JCurl.java   Source Code and License 6 votes vote down vote up
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.
    }
  }
}
 
Example 36
Project: Redunda-lib-java   File: DataService.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 37
Project: hadoop-oss   File: ReEncryptionClientProvider.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 38
Project: invest-stash-rest   File: HttpRequests.java   Source Code and License 6 votes vote down vote up
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);
   }
 
Example 39
Project: EMC-Marketplace-Mod   File: Web.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 40
Project: ServerConnect   File: Metrics.java   Source Code and License 6 votes vote down vote up
/**
 * 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 :)
}