当前位置: 首页>>代码示例>>Java>>正文


Java HttpsURLConnection类代码示例

本文整理汇总了Java中javax.net.ssl.HttpsURLConnection的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection类的具体用法?Java HttpsURLConnection怎么用?Java HttpsURLConnection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpsURLConnection类属于javax.net.ssl包,在下文中一共展示了HttpsURLConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: disableCertificateValidation

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
public static void disableCertificateValidation() 
{
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] 
    { 
      new TrustAllManager() 
    };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new TrustAllHostnameVerifier();
    
    // Install the all-trusting trust manager
    try 
    {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
}
 
开发者ID:johndavidbustard,项目名称:RoughWorld,代码行数:21,代码来源:WebClient.java

示例2: sendData

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 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 :)
}
 
开发者ID:codeHusky,项目名称:HuskyUI-Plugin,代码行数:32,代码来源:Metrics.java

示例3: createHttpUrlConnection

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
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;
}
 
开发者ID:Leanplum,项目名称:Leanplum-Android-SDK,代码行数:24,代码来源:Util.java

示例4: execute

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 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;
	}
}
 
开发者ID:SOBotics,项目名称:Redunda-lib-java,代码行数:65,代码来源:PingService.java

示例5: get

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
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();
}
 
开发者ID:Moudoux,项目名称:EMC,代码行数:23,代码来源:WebUtils.java

示例6: createConnectionGet

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 创建连接
 *
 * @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;
}
 
开发者ID:wangfei0904306,项目名称:unionpay,代码行数:32,代码来源:HttpClient.java

示例7: 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

示例8: getAllKfAccount

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 获取所有客服帐号
 *
 * @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;
}
 
开发者ID:youngMen1,项目名称:JAVA-,代码行数:29,代码来源:WeiXinKFUtils.java

示例9: HttpResponse

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
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();
    }
}
 
开发者ID:rzari,项目名称:jarling,代码行数:22,代码来源:HttpResponse.java

示例10: initBmob

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 初始化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();
}
 
开发者ID:IaHehe,项目名称:classchecks,代码行数:27,代码来源:Bmob.java

示例11: publicApiQuery

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 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) {}
        }
    }
}
 
开发者ID:dylanjsa,项目名称:cryptopia4j,代码行数:32,代码来源:CryptopiaClient.java

示例12: execute

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
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();
        }
    }
}
 
开发者ID:B-V-R,项目名称:VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java,代码行数:24,代码来源:HttpClient.java

示例13: reSend

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 重发
 * 
 * @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);
		}
	}
}
 
开发者ID:iBase4J,项目名称:iBase4J-Common,代码行数:42,代码来源:WeiXinCompanySendMsg.java

示例14: doClient

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
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");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:HttpsSocketFacTest.java

示例15: sendData

import javax.net.ssl.HttpsURLConnection; //导入依赖的package包/类
/**
 * 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 :)
}
 
开发者ID:RadBuilder,项目名称:EmojiChat,代码行数:37,代码来源:Metrics.java


注:本文中的javax.net.ssl.HttpsURLConnection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。