使用jsoup解析http/https协议网页内容通用方法_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 使用jsoup解析http/https协议网页内容通用方法

使用jsoup解析http/https协议网页内容通用方法

 2013/8/1 22:10:28  hou_jian_yong  程序员俱乐部  我要评论(0)
  • 摘要:importjava.net.MalformedURLException;importjava.net.URL;importjava.security.SecureRandom;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjava.util.Map;importjavax.net.ssl.HostnameVerifier;importjavax.net
  • 标签:方法 使用 内容 网页 协议 解析 JS HTTP
class="java" name="code">import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.jsoup.Connection;
import org.jsoup.helper.HttpConnection;

public class HTTPCommonUtil {
	public static void trustEveryone() {
		try {
			HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});

			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new X509TrustManager[] { new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	public static Object getHttpHeaders(URL url, int timeout) {
		try {
			trustEveryone();
			Connection conn = HttpConnection.connect(url);
			conn.timeout(timeout);
			conn.header("Accept-Encoding", "gzip,deflate,sdch");
			conn.header("Connection", "close");
			conn.get();
			Map<String, String> result = conn.response().headers();
			result.put("title", conn.response().parse().title());
			return result;

		} catch (Exception e) {
			//e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		try {
			URL url = new URL("https", "202.133.116.70", -1, "");
			System.out.println(getHttpHeaders(url, 10000));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}

?

上一篇: java实现单例 下一篇: JAVA排序
发表评论
用户名: 匿名