
HTTP通信
GET请求
- 创建url对象
- 通过url对象打开链接并得到HTTPUrlConnection对象
- 设置相关属性(请求方式 get/post 请求参数)
- 连接
- 接受服务器响应信息
- 销毁连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19Url url = new Url("xxxxx");
HTTPUrlConnection conn = url.openConnection(); //得到HTTPUrlConnection
conn.setDoInput(true); //设置输入流
conn.setRequestMethod("GET/POST"); //设置请求方式,注意全大写
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置请求属性(数据的提交方式)
conn.connect(); //连接
InputStream input = conn.getInputStream();
byte[] bufin = new byte[1024];
int len = 0;
StringBuilder sb = new StringBuilder();
if( (len = input.read(bufin)) != -1 ){ //循环读取inputStream(很重要的算法)
sb.append(new String(bufin));
bufin = new byte[1024];
}
System.out.println("接受到的数据: " + sb.toString());
conn.disConnect() //销毁连接
POST请求
1 |
URL url = new URL("xxxxx"); |
properties.setProperty(key, value);
k:mail.debug v:true //debug开关
k:mail.host v:发送或者接收服务器地址 //smtp.qq.com(发送) pop.qq.com(接收)
k:mail.transport.protocol v:smtp //发送时用的协议
k:mail.store.protocol v:pop3 //接收时用的协议
k:mail.debug.auth v:true //认证协议`
- 创建一个Session对象
- Session对象创建一个Transport对象/Store对象,用于发送/接受邮件
- Transport对象/Store 连接服务器
- Transport对象/Store 创建MimeMessage对象
- Transport发送邮件, Store接收邮件
- 接收邮件的协议:pop
- 发送邮件的协议:smtp




近期评论