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


Java HttpsURLConnection.disconnect方法代码示例

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


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

示例1: importToCloudCard

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String importToCloudCard(CardHolder cardHolder, Properties properties) {

        try {

            URL url = new URL(properties.getProperty(BASE_URL) + "/api/people");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            setConnectionHeaders(connection, properties);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(cardHolder.toJSON().getBytes());
            outputStream.flush();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                return "Failed : HTTP error code : " + connection.getResponseCode();
            }

            connection.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Success";
    }
 
开发者ID:sharptopco,项目名称:cloudcard-csv-importer,代码行数:26,代码来源:Main.java

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

示例3: post

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static String post(String requestUrl, String payload, CookieManager cookies) throws Exception {
	URL url = new URL(urlEncode(requestUrl));
	HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
	if (cookies != null)
		applyCookies(connection);

	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setRequestMethod("POST");
	connection.setRequestProperty("Accept", "application/json");
	connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

	OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
	writer.write(payload);
	writer.close();

	BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	StringBuilder jsonString = new StringBuilder();
	String line;
	while ((line = br.readLine()) != null)
		jsonString.append(line);

	br.close();
	connection.disconnect();

	storeCookies(connection);
	return jsonString.toString();
}
 
开发者ID:Moudoux,项目名称:EMC,代码行数:29,代码来源:WebUtils.java

示例4: doGet

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
 * Get 请求
 *
 * @param pathUrl
 * @param queryString
 * @return
 */
public static String doGet(String pathUrl, String queryString) {
    StringBuilder repString = new StringBuilder();
    String path = pathUrl;
    if (null != queryString && !"".equals(queryString)) {
        path = path + "?" + queryString;
    }
    HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
    try {
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(path)).openConnection();

        TrustManager[] tm = {ignoreCertificationTrustManger};
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tm, new java.security.SecureRandom());

        // 从上述SSLContext对象中得到SSLSocketFactory对象 
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        connection.setSSLSocketFactory(ssf);

        InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String s;
        while (null != (s = br.readLine())) {
            repString.append(s);
        }
        isr.close();
        connection.disconnect();
    } catch (Exception ex) {
        log.error("调用链接失败:pathUrl:" + pathUrl + "queryString:" + queryString);
        log.error(ex.getMessage());
    } finally {
        log.info(repString.toString());
    }
    return repString.toString();
}
 
开发者ID:tong12580,项目名称:OutsourcedProject,代码行数:42,代码来源:HttpUtil.java

示例5: URLGet

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
     * GET List<NameValuePair>请求
     *
     * @param pathUrl
     * @param params
     * @return
     */
    public static String URLGet(String pathUrl, List<NameValuePair> params) {

        String queryString = "";

        StringBuilder repString = new StringBuilder();

        try {
            String path = pathUrl;
            String keyValue;
            if (null != params && params.size() > 0) {

                for (NameValuePair nvp : params) {
                    String key = nvp.getName();
                    keyValue = nvp.getValue();
                    if (null != keyValue && !"".equals(keyValue)) {
                        queryString = queryString + key + "=" + keyValue + "&";
                    }
                }
            }
            if (!"".equals(queryString)) {
                path = path + "?" + queryString;
            }
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) (new URL(path)).openConnection();

            // Prepare SSL Context 
            TrustManager[] tm = {ignoreCertificationTrustManger};
//            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); 
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, new java.security.SecureRandom());


            // 从上述SSLContext对象中得到SSLSocketFactory对象 
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);

            InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String s;
            while (null != (s = br.readLine())) {
                repString.append(s);
            }
            isr.close();
            connection.disconnect();

        } catch (Exception ex) {
            log.error("调用链接失败:pathUrl:" + pathUrl + "queryString:" + queryString);
            ex.printStackTrace();
        } finally {
            log.info(repString.toString());
        }
        return repString.toString();
    }
 
开发者ID:tong12580,项目名称:OutsourcedProject,代码行数:61,代码来源:HttpUtil.java

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

示例7: upload

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static String upload(String fileName, File file) throws IOException {
	String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + WeiXinCompanyUtils.getToken()
			+ "&type=file";
	// 定义数据分隔符
	String boundary = "------------7da2e536604c8";
	URL uploadUrl = new URL(urlStr);
	HttpsURLConnection uploadConn = (HttpsURLConnection) uploadUrl.openConnection();
	uploadConn.setDoOutput(true);
	uploadConn.setDoInput(true);
	uploadConn.setRequestMethod("POST");
	// 设置请求头Content-Type
	uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	// 获取媒体文件上传的输出流(往微信服务器写数据)
	OutputStream outputStream = uploadConn.getOutputStream();

	// 从请求头中获取内容类型
	String contentType = "text";
	// 根据内容类型判断文件扩展名
	@SuppressWarnings("unused")
	String[] f = fileName.split("\\.");
	// 请求体开始
	outputStream.write(("--" + boundary + "\r\n").getBytes());
	// String aaa = String.format("Content-Disposition: form-data;
	// name=\"media\"; filename=\""+f[0]+"."+"%s\"\r\n", f[1]);
	String aaa = "Content-Disposition: form-data; name=\"media\"; filename=\"" + fileName + "\"\r\n";
	outputStream.write(aaa.getBytes());
	String bbb = String.format("Content-Type: %s\r\n\r\n", contentType);
	outputStream.write(bbb.getBytes());

	// 获取媒体文件的输入流(读取文件)
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
	byte[] buf = new byte[8096];
	int size = 0;
	while ((size = bis.read(buf)) != -1) {
		// 将媒体文件写到输出流(往微信服务器写数据)
		outputStream.write(buf, 0, size);
	}
	// 请求体结束
	outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
	outputStream.close();
	bis.close();

	// 获取媒体文件上传的输入流(从微信服务器读数据)
	InputStream inputStream = uploadConn.getInputStream();
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	StringBuffer buffer = new StringBuffer();
	String str = null;
	while ((str = bufferedReader.readLine()) != null) {
		buffer.append(str);
	}
	bufferedReader.close();
	inputStreamReader.close();
	// 释放资源
	inputStream.close();
	uploadConn.disconnect();

	System.out.println(buffer.toString());
	return buffer.toString();
}
 
开发者ID:iBase4J,项目名称:iBase4J-Common,代码行数:61,代码来源:WeiXinCompanyUpload.java

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

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

示例11: upload

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static String upload(File file) throws IOException {
	String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + WeiXinCompanyUtils.getToken()
			+ "&type=file";
	// 定义数据分隔符
	String boundary = "------------7da2e536604c8";
	URL uploadUrl = new URL(urlStr);
	HttpsURLConnection uploadConn = (HttpsURLConnection) uploadUrl.openConnection();
	uploadConn.setDoOutput(true);
	uploadConn.setDoInput(true);
	uploadConn.setRequestMethod("POST");
	// 设置请求头Content-Type
	uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	// 获取媒体文件上传的输出流(往微信服务器写数据)
	OutputStream outputStream = uploadConn.getOutputStream();

	// 从请求头中获取内容类型
	String contentType = "text";
	// 根据内容类型判断文件扩展名
	String ext = file.getName().substring(file.getName().lastIndexOf("."));
	String name = file.getName();

	// 请求体开始
	outputStream.write(("--" + boundary + "\r\n").getBytes());
	String aaa = String
			.format("Content-Disposition: form-data; name=\"media\"; filename=\"" + name + "." + "%s\"\r\n", ext);
	outputStream.write(aaa.getBytes());
	String bbb = String.format("Content-Type: %s\r\n\r\n", contentType);
	outputStream.write(bbb.getBytes());

	// 获取媒体文件的输入流(读取文件)
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
	byte[] buf = new byte[8096];
	int size = 0;
	while ((size = bis.read(buf)) != -1) {
		// 将媒体文件写到输出流(往微信服务器写数据)
		outputStream.write(buf, 0, size);
	}
	// 请求体结束
	outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
	outputStream.close();
	bis.close();

	// 获取媒体文件上传的输入流(从微信服务器读数据)
	InputStream inputStream = uploadConn.getInputStream();
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	StringBuffer buffer = new StringBuffer();
	String str = null;
	while ((str = bufferedReader.readLine()) != null) {
		buffer.append(str);
	}
	bufferedReader.close();
	inputStreamReader.close();
	// 释放资源
	inputStream.close();
	uploadConn.disconnect();

	System.out.println(buffer.toString());
	return buffer.toString();
}
 
开发者ID:tb544731152,项目名称:iBase4J,代码行数:61,代码来源:WeiXinCompanyUpload.java

示例12: sendPost

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private boolean sendPost(String domain,String subdomain,String ip,String key,String secret) throws Exception {
        String url = String.format("https://api.godaddy.com/v1/domains/%s/records/A/%s",domain,subdomain);
        String json ="[{" +
                "\"data\":\""+ip+"\","+
                "\"ttl\":600,"+
                "\"name\":\"@\","+
                "\"type\":\"A\""+
                "}]";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();


        con.setRequestMethod("PUT");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Content-Type","application/json");
        con.setRequestProperty("Accept","application/json");
        con.setRequestProperty("Authorization", String.format("sso-key %s:%s",key,secret));
//        con.setRequestProperty("Connection", "close");
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(json);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        System.out.println("\nSending 'PUT' request to URL : " + url);
        System.out.println("Post parameters : " + json);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        con.disconnect();

        System.out.println(response.toString());

        if(responseCode ==200){
            System.out.println(String.format("Change dns %s.%s to %s:\r\n"+response.toString(),subdomain,domain,ip));

            return true;
        }else {
            System.out.println("Not able to update the godaddy dns ");
            System.out.println("Response Code : " + responseCode);
            return false;
        }
    }
 
开发者ID:forqzy,项目名称:godaddy-ddns,代码行数:56,代码来源:Godaddy_ddns.java

示例13: httpsRequest

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	JSONObject jsonObject = null;
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new HttpsX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
		conn.setUseCaches(false);
		conn.setRequestProperty("Content-Type", "application/json;;charset=UTF-8");
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		jsonObject = JSONObject.parseObject(buffer.toString());
	} catch (ConnectException ce) {
		ce.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return jsonObject;
}
 
开发者ID:Fetax,项目名称:Fetax-AI,代码行数:51,代码来源:HttpUtil.java


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