一开始写了一个用socket下载数据的代码,是成功可以下载到数据了
public String Request(String url)
{
String str;
PrintWriter out = null;
if(socket != null)
{
try {
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("GET /v1.0/");
out.print(url);
out.print(" HTTP/1.1\r\n");
out.print("Host:api.yeelink.net\r\n");
out.print("Accept: */*\r\n");
out.print("U-ApiKey:***************\r\n"); //抱歉!key不能公布,用**代替
out.print("Content-Length:0\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.println("print get done.\r\n");
out.flush();
str = Receive();
if( ( (String)str.subSequence(9, 12) ).equals("200") )
{
//数据解析
}
else
{
try {
socket = new Socket("42.96.164.52",80);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = Request(url);
}
return str;
}
return null;
}
后来在下载图片的时候,由于不知道怎么截取到图片的数据,所以想改用HttpURLConnection进行下载,这时候就出问题了
public static byte[] HttpReceive()
{
byte[] v = null;
try {
URL url = new URL("http://api.yeelink.net/v1.0/device/342273/sensor/379602/photo/content/2015-11-27T08:54:32");
HttpURLConnection hc = (HttpURLConnection)url.openConnection();
hc.setRequestMethod("GET");
hc.setDoInput(true);
hc.setUseCaches(false);
hc.setInstanceFollowRedirects(true);
hc.setRequestProperty("Host", "api.yeelink.net");
hc.setRequestProperty("Accept", "*/*");
hc.setRequestProperty("U-ApiKey", "******");
hc.setRequestProperty("Content-Length", "0");
hc.setRequestProperty("Connection", "close");
// hc.setRequestProperty("Content-type", "image/jpeg");
hc.connect();
InputStream is = hc.getInputStream();
int streamLength = (int)is.available();
byte[] b = new byte[streamLength];
is.read(b, 0, streamLength);
return b;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return v;
}
出现了filenotfoundexception异常
有人知道是什么原因吗
你没有判断返回码,确定拿到数据了吗?都报文件找不到异常了,再检查一下吧。
byte[] v = null;
你的v一直为null啊,你要把b赋值给v
你请求的数据是图片的话,那你的url后面的文件名的后缀应该加上去
"http://api.yeelink.net/v1.0/device/342273/sensor/379602/photo/content/2015-11-27T08:54:32"
换成post试一下, hc.setRequestMethod("post");
莫名其妙又可以了。。。。