當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpsURLConnection.connect方法代碼示例

本文整理匯總了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;
}
 
開發者ID:goxr3plus,項目名稱:java-google-speech-api,代碼行數:27,代碼來源:GSpeechDuplex.java

示例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;
}
 
開發者ID:Pverweij,項目名稱:TrustPilotFinder,代碼行數:24,代碼來源:Main.java

示例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();
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:18,代碼來源:HttpsCreateSockTest.java

示例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());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:32,代碼來源:URLConnectionTest.java

示例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;
    }
  }
}
 
開發者ID:rakutentech,項目名稱:android-perftracking,代碼行數:71,代碼來源:EventWriter.java

示例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;
}
 
開發者ID:nextgis,項目名稱:android_nextgis_mobile,代碼行數:31,代碼來源:NGIDUtils.java

示例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);
	}
}
 
開發者ID:youseries,項目名稱:ureport,代碼行數:13,代碼來源:HttpsImageProvider.java

示例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();
}
 
開發者ID:bubicn,項目名稱:bubichain-sdk-java,代碼行數:46,代碼來源:HttpKit.java

示例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();
}
 
開發者ID:bubicn,項目名稱:bubichain-sdk-java,代碼行數:52,代碼來源:HttpKit.java

示例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;
    }
 
開發者ID:tojaoomy,項目名稱:private-WeChat,代碼行數:68,代碼來源:CommonUtil.java

示例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;
}
 
開發者ID:Evan1120,項目名稱:wechat-api-java,代碼行數:49,代碼來源:WeixinUtil.java

示例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();
  }
}
 
開發者ID:XecureIT,項目名稱:PeSanKita-lib,代碼行數:48,代碼來源:PushServiceSocket.java

示例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;
}
 
開發者ID:Wurst-Imperium,項目名稱:Wurst-MC-1.12,代碼行數:61,代碼來源:GuiWurstMainMenu.java

示例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;
}
 
開發者ID:milesmcc,項目名稱:LibreNews-Android,代碼行數:28,代碼來源:FlashRetreiver.java


注:本文中的javax.net.ssl.HttpsURLConnection.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。