最近在网上接触了开源硬件Arduino, 觉得很好玩,就弄了个板子玩玩,进而接触的yeelink 。yeelink是一个很好玩的物联网云平台,通过HTTP协议发送接收。由于本人对HTTP协议不熟悉,遂通过实际代码学习yeelink通信原理。
JAVA实现的简单测试代码:
发送一个查询设备数据点的HTTP请求,
服务器回复所查询的设备信息。
三个步骤:第一部分,进行DNS地址解析;第二部分,发送HTTP请求;第三部分,接收HTTP响应。
输出结果:
api.yeelink.net/42.96.164.52
GET /v1.1/device/15527/sensor/26738/datapoints HTTP/1.1
U-ApiKey: 29f95415ec8xxxxxxxxxxxxxxxxxxxx
Host: api.yeelink.net
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Sat, 08 Nov 2014 15:45:10 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.3.10-1ubuntu3.6
55
{"value":1,"timestamp":"2014-11-08T22:18:08","sensor_id":"26738","device_id":"15527"}
0
-----------------------------------------------------------------------------------------------------------------------------------
package HTTPTEST;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MAIN {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
<span style="white-space:pre"> </span>String host_name = "api.yeelink.net";
// HTTP请求 http://api.yeelink.net/v1.1/device/15527/sensor/26738/datapoints
String send_buf = "GET /v1.1/device/15527/sensor/26738/datapoints HTTP/1.1\r\nU-ApiKey: xxxxxxxxxxxxxxxx\r\nHost: api.yeelink.net\r\n\r\n";
char[] cbuf = null;
cbuf = new char[1024];
InetAddress myServer = null;
//DNS解析出IP
myServer = InetAddress.getByName(host_name);
System.out.println(myServer);
//创建套接字
Socket socket = new Socket(myServer, 80);
//创建套接字读写流
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//发送请求
out.println(send_buf);
System.out.print(send_buf);
//读服务器返回值
in.read(cbuf);
System.out.println(cbuf);
}
}
参考博客:http://blog.csdn.net/xukai871105/article/details/17096319
http://blog.csdn.net/xukai871105/article/details/8607338