关于SSL安全套接字的代码 不懂啊 能给解释下么

guo505088726 2013-12-14 02:41:00
/**
* 通过 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;
}
...全文
212 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Defonds 2013-12-14
  • 打赏
  • 举报
回复
官方应该给 demo 了吧
guo505088726 2013-12-14
  • 打赏
  • 举报
回复
我是个菜鸟啊 刚工作 想问下 这个方法什么作用啊 返回的是什么? 我要想弄懂他 要学习些什么 求帮忙啊

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧