Blackdogman’s blog

HTTP通信

GET请求

  1. 创建url对象
  2. 通过url对象打开链接并得到HTTPUrlConnection对象
  3. 设置相关属性(请求方式 get/post 请求参数)
  4. 连接
  5. 接受服务器响应信息
  6. 销毁连接
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Url 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
URL url = new URL("xxxxx");
HTTPUrlConnection conn = url.openConnetion();
conn.setDoOutPut(true);
conn.setDoInPut(true);
conn.setRequestMethod("POST");
conn.setUseCaches(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置请求属性(数据的提交方式)

conn.connect();

//================这段记住=============
String pram = "name=" + URLEncoder.encode("value", "codeType(utf-8)")
+"&name2=" + URLEncoder.encode...;
//=====================================
DataOutputStream output = new DataOutputStream(conn.getOutputStream());
output.write(parm.getBytes());
output.flush();
output.close();

InputStream input = conn.getInputStream();
Byte[] bufin = new Byte[256];
input.read(bufin);

System.out.println(new String(bufin, "utf-8").tirm());
input.close();
```

### JAVA 邮件收发
#### mail.jar
1. 创建Properties对象,设置属性

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 //认证协议
`

  1. 创建一个Session对象
  2. Session对象创建一个Transport对象/Store对象,用于发送/接受邮件
  3. Transport对象/Store 连接服务器
  4. Transport对象/Store 创建MimeMessage对象
  5. Transport发送邮件, Store接收邮件
  • 接收邮件的协议:pop
  • 发送邮件的协议:smtp