本文整理汇总了Java中javax.net.ssl.HttpsURLConnection.connect方法的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection.connect方法的具体用法?Java HttpsURLConnection.connect怎么用?Java HttpsURLConnection.connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.HttpsURLConnection
的用法示例。
在下文中一共展示了HttpsURLConnection.connect方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getHttpsURLConnection
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* @param sampleRate
* The samleRate
* @param url
* The URL
* @return The HTTPSURLConnection
* @throws IOException
* if something goes wrong in reading the file.
*/
private HttpsURLConnection getHttpsURLConnection(int sampleRate , URL url) throws IOException {
URLConnection urlConn = url.openConnection();
if (! ( urlConn instanceof HttpsURLConnection )) {
throw new IOException("URL is not an Https URL");
}
HttpsURLConnection httpConn = (HttpsURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setChunkedStreamingMode(0);
httpConn.setRequestProperty("Transfer-Encoding", "chunked");
httpConn.setRequestProperty("Content-Type", "audio/x-flac; rate=" + sampleRate);
// also worked with ("Content-Type", "audio/amr; rate=8000");
httpConn.connect();
return httpConn;
}
示例2: linkIsReview
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
static boolean linkIsReview(String link)
{
try
{
HttpURLConnection con = (HttpURLConnection) new URL(link).openConnection();
HttpsURLConnection sslCon = (HttpsURLConnection) con;
sslCon.setInstanceFollowRedirects(false);
sslCon.connect();
if(con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
{
String newUrl = con.getHeaderField("Location");
newUrl = "https://nl.trustpilot.com" + newUrl;
con.disconnect();
return true;
}
}
catch (Exception ex)
{
System.out.println(ex);
}
return false;
}
示例3: doClient
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
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();
}
示例4: inspectHandshakeThroughoutRequestLifecycle
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@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());
}
示例5: begin
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
void begin() throws IOException {
try {
_conn = (HttpsURLConnection) _url.openConnection();
_conn.setRequestMethod("POST");
for (Map.Entry<String, String> entry : _config.header.entrySet()) {
_conn.setRequestProperty(entry.getKey(), entry.getValue());
}
_conn.setUseCaches(false);
_conn.setDoInput(false);
_conn.setDoOutput(true);
_conn.connect();
_writer = new BufferedWriter(new OutputStreamWriter(_conn.getOutputStream()));
_writer.append("{\"app\":\"").append(_config.app)
.append("\",\"version\":\"").append(_config.version)
.append("\",\"relay_app_id\":\"").append(_config.relayAppId);
if (_envInfo.device != null) {
_writer.append("\",\"device\":\"").append(_envInfo.device);
}
if (_envInfo.getAppUsedMemory() > 0) {
_writer.append("\",\"app_mem_used\":\"").append(Long.toString(_envInfo.getAppUsedMemory()));
}
if (_envInfo.getDeviceFreeMemory() > 0) {
_writer.append("\",\"device_mem_free\":\"").append(Long.toString(_envInfo.getDeviceFreeMemory()));
}
if (_envInfo.getDeviceTotalMemory() > 0) {
_writer.append("\",\"device_mem_total\":\"").append(Long.toString(_envInfo.getDeviceTotalMemory()));
}
if (_envInfo.getBatteryLevel() > 0) {
_writer.append("\",\"battery_level\":\"").append(Float.toString(_envInfo.getBatteryLevel()));
}
if (_envInfo.getCountry() != null) {
_writer.append("\",\"country\":\"").append(_envInfo.getCountry());
}
if (_envInfo.getRegion() != null) {
_writer.append("\",\"region\":\"").append(_envInfo.getRegion());
}
if (_envInfo.network != null) {
_writer.append("\",\"network\":\"").append(_envInfo.network);
}
if (_envInfo.osName != null) {
_writer.append("\",\"os\":\"").append(_envInfo.osName);
}
if (_envInfo.osVersion != null) {
_writer.append("\",\"os_version\":\"").append(_envInfo.osVersion);
}
_writer.append("\",\"measurements\":[");
_measurements = 0;
} catch (Exception e) {
if (_config.debug) {
Log.d(TAG, e.getMessage());
}
disconnect();
if (e instanceof IOException) {
throw e;
}
}
}
示例6: getData
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String getData(
String target,
String method,
String token)
{
try {
URL url = new URL(target);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
if (!TextUtils.isEmpty(token)) {
conn.setRequestProperty("Authorization", token);
}
conn.setRequestMethod(method);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line, data = "";
while ((line = in.readLine()) != null) {
data += line;
}
in.close();
return data;
} catch (IOException ignored) {
ignored.printStackTrace();
}
return null;
}
示例7: getImage
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Override
public InputStream getImage(String path) {
try{
URL url=new URL(path);
HttpsURLConnection connection=(HttpsURLConnection)url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
return inputStream;
}catch(Exception ex){
throw new ReportException(ex);
}
}
示例8: get
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丟et璇锋眰
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(25000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setHostnameVerifier(new Verifier());
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
示例9: post
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丳ost璇锋眰
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(50000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(50000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setHostnameVerifier(new Verifier());
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
示例10: httpsRequest
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 发起https请求并获取结果
*
* @param requestUrl
* 请求地址
* @param requestMethod
* 请求方式(GET、POST)
* @param outputStr
* 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new SaicX509TrustManager() };
// SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
logger.error("connection timed out cause by " + ce.getMessage());
} catch (Exception e) {
logger.error("https request error : " + e.getMessage());
}
return jsonObject;
}
示例11: httpsRequest
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
示例12: uploadAttachment
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private byte[] uploadAttachment(String method, String url, InputStream data,
long dataSize, byte[] key, ProgressListener listener)
throws IOException
{
URL uploadUrl = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
connection.setDoOutput(true);
if (dataSize > 0) {
connection.setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize));
} else {
connection.setChunkedStreamingMode(0);
}
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Connection", "close");
connection.connect();
try {
OutputStream stream = connection.getOutputStream();
AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream);
byte[] buffer = new byte[4096];
int read, written = 0;
while ((read = data.read(buffer)) != -1) {
out.write(buffer, 0, read);
written += read;
if (listener != null) {
listener.onAttachmentProgress(dataSize, written);
}
}
data.close();
out.flush();
out.close();
if (connection.getResponseCode() != 200) {
throw new IOException("Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
}
return out.getAttachmentDigest();
} finally {
connection.disconnect();
}
}
示例13: updateScreen
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Override
public void updateScreen()
{
super.updateScreen();
// updater
if(startupMessageDisabled)
return;
if(WurstClient.INSTANCE.updater.isOutdated())
{
WurstClient.INSTANCE.analytics.trackEvent("updater",
"update to v" + WurstClient.INSTANCE.updater.getLatestVersion(),
"from " + WurstClient.VERSION);
WurstClient.INSTANCE.updater.update();
startupMessageDisabled = true;
}
// emergency message
if(startupMessageDisabled)
return;
try
{
HttpsURLConnection connection = (HttpsURLConnection)new URL(
"https://www.wurstclient.net/api/v1/messages.json")
.openConnection();
connection.connect();
JsonObject json = JsonUtils.jsonParser
.parse(
new InputStreamReader(connection.getInputStream(), "UTF-8"))
.getAsJsonObject();
if(json.get(WurstClient.VERSION) != null)
{
System.out.println("Emergency message found!");
mc.displayGuiScreen(new GuiMessage(
json.get(WurstClient.VERSION).getAsJsonObject()));
startupMessageDisabled = true;
}
}catch(Exception e)
{
e.printStackTrace();
}
// changelog
if(startupMessageDisabled)
return;
if(!WurstClient.VERSION
.equals(WurstClient.INSTANCE.options.lastLaunchedVersion))
{
mc.displayGuiScreen(new GuiYesNo(this,
"Successfully updated to Wurst v" + WurstClient.VERSION, "",
"Go Play", "View Changelog", 64));
WurstClient.INSTANCE.options.lastLaunchedVersion =
WurstClient.VERSION;
ConfigFiles.OPTIONS.save();
}
startupMessageDisabled = true;
}
示例14: retreiveFlashesNonAsync
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private boolean retreiveFlashesNonAsync(Context context) throws IOException, JSONException, ParseException{
if (!serverLocation.getProtocol().equals("https")) {
throw new SecurityException("Flashes may only be retrieved over a secure HTTPS connection!");
}
sendDebugNotification("Retrieving flashes from " + serverLocation, context);
HttpsURLConnection urlConnection = (HttpsURLConnection) serverLocation.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(150000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String data = sb.toString();
JSONObject jsonData = new JSONObject(data);
serverName = jsonData.getString("server");
flashes = convertJsonToFlashes(jsonData.getJSONArray("latest"));
}
sendDebugNotification("Flashes found: " + flashes.length, context);
return true;
}