日期:2014-05-17  浏览次数:20735 次

关于SSL安全套接字的代码 不懂啊 能给解释下么
/**
 * 通过 URL 调用不同的接口  GET
 * 
 * 将调用腾讯接口 返回解析 修改为json --2013-9-29
 * @param urls
 * @return 
 */
public static JSONObject weChatInterfaceInvoke(String urls){
JSONObject jsonObject = null;
InputStream is= null;
DataInputStream indata= null;
HttpsURLConnection conn=null;
String str_return="";
try{

SSLContext sc = null;
//SSLContext.getInstance("SSL");返回实现指定安全套接字协议的 SSLContext 对象。
sc = SSLContext.getInstance("SSL");
//init()方法初始化此上下文
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
//openConnection()方法返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 
//每次调用此 URL 的协议处理程序的 openConnection 方法都打开一个新的连接。

URL console = new URL(urls);
conn = (HttpsURLConnection) console
.openConnection();

conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
//打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 
//如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。

conn.connect();
//返回从此打开的连接读取的输入流
is = conn.getInputStream();
//DataInputStreat 数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。
//应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。
indata = new DataInputStream(is);
String ret = "";
//indata.readLine()从包含的输入流中读取此操作需要的字节。
while ((ret = indata.readLine()) != null) {
str_return += ret;
}
//str_return.getBytes("ISO-8859-1");使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
//new String(byte[] bytes, String charsetName) throws UnsupportedEncodingException  
//通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
str_return =  new String(str_return.getBytes("ISO-8859-1"), "utf-8");
jsonObject = JSONObject.fromObject(str_return.toString());
}catch(Exception e){
e.printStackTrace();
}finally{
try {
//每次打开流后,都需要关闭,然后赋值NULL,等GC回收
if(null !=indata){
indata.close();
indata=null;
}
if(null !=is){
is.close();
is=null;
}
if(null !=conn){
conn.disconnect();
conn=null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}