使用http链接, 访问网站的json数据并转换成实体类对象
API接口官网: http://www.tngou.net/
public static<T> T getDataFromHttp(String url, String method, Map<String, ?> parameter, Class<T> type){
StringBuilder builder = new StringBuilder();
Set<? extends Map.Entry<String, ?>> set = parameter.entrySet();
for (Map.Entry<String, ?> stringEntry : set) {
builder.append(stringEntry.getKey())
.append("=")
.append(stringEntry.getValue())
.append("&");
}
builder.deleteCharAt(builder.length() - 1);//删掉最后一个&符号
if (method.equals("GET")) {
url = url + "?" + builder.toString();
}
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setDoInput(true);
if (method.equals("POST")) {
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(builder.toString().getBytes("UTF-8"));
}
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
byte[] buffer = new byte[102400];
int length;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((length = is.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
String json = bos.toString("UTF-8");
Gson gson = new Gson();
return gson.fromJson(json, type);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
文件下载, 支持断线续传, 显示进度条和下载
package org.lulu.learn;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Project: Day17_HTTP
* Created: Lulu
* Date: 2016/8/18
*/
public class DownloadTest {
public static void main(String[] args) {
try {
File file = new File("res/NeoImaging_Setup.exe");
HttpURLConnection connection = (HttpURLConnection) new URL("http://skycnxz2.wy119.com//4/NeoImaging_Setup.zip").openConnection();
connection.setRequestMethod("GET");
//进度条设置
long sum = 0;
if (file.exists()) {
sum = file.length();
//bytes=0- 表示起始位置到末尾
connection.setRequestProperty("Range", "bytes=" + file.length() + "-" );
}
int code = connection.getResponseCode();
// System.out.println("code=" + code);
if (code == 200 || code == 206) {
// //获取得到头部数据
// Map<String, List<String>> fields = connection.getHeaderFields();
// Set<Map.Entry<String, List<String>>> entries = fields.entrySet();
// for (Map.Entry<String, List<String>> entry : entries) {
// System.out.println(entry.getKey() + ":" + entry.getValue());
// }
/*
Accept-Ranges [bytes]: (有该项)说明支持断点下载, 不一定从头部去下载
Content-Length:[34493195]: 文件长度, 有长度不一定支持断点下载, 没有长度一定不支持断点下载
*/
//获取文件长度
int contentLength = connection.getContentLength();
contentLength += sum;
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(file, true);//apend将是否续写设置为true
byte[] buffer = new byte[102400];
int length;
long startTime = System.currentTimeMillis();
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
sum += length;
float percent = sum * 100.0f / contentLength;
System.out.print("\r[");
int p = (int) (percent / 2);
for (int i = 0; i < 50; i++) {
if (i < p) {
System.out.print("=");
} else if (i == p) {
System.out.print(">");
} else {
System.out.print(" ");
}
}
System.out.print("]");
System.out.printf("\t%.2f%%", percent);
//速度显示
long speed = sum * 1000 / (System.currentTimeMillis() - startTime);
if (speed > (1 << 20)) {//1024 * 1024
System.out.printf("\t%d MB/s", speed >> 20);
} else if (speed > (1 << 10)){
System.out.printf("\t%d KB/s", speed >> 10);
} else {
System.out.printf("\t%d B/s", speed);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行效果
多线程下载
DownloadRunnable .java
package org.lulu.learn;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* Project: Day17_HTTP
* Created: Lulu
* Date: 2016/8/18
*/
public class DownloadRunnable implements Runnable {
private String url;
//需要保存的文件
private File file;
//开始的位置和终止的位置
private int start;
private int end;
public DownloadRunnable(String url, File file, int start, int end) {
this.url = url;
this.file = file;
this.start = start;
this.end = end;
}
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
//将位置移动到start位置
accessFile.seek(start);
int code = connection.getResponseCode();
if (code == 206) {
InputStream is = connection.getInputStream();
byte[] buffer = new byte[102400];
int length;
while ((length = is.read(buffer)) != -1) {
accessFile.write(buffer, 0, length);
}
}
System.out.println("下载完成" + start);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ThreadDownload.java
/**
* Project: Day17_HTTP
* Created: Lulu
* Date: 2016/8/18
* 多线程下载
* 多线程下载
*/
public class ThreadDownload {
public static void main(String[] args) {
try {
String url = "http://skycnxz3.wy119.com/OrcsMustDie2Tr.zip";
File file = new File("res/game.zip");
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
int contentLength = connection.getContentLength();
int range = contentLength / 5;//分成5块. 最后一个线程下载完
for (int i = 0; i < 5; i++) {
int start = i * range;
int end = start + range;
if (i == 4) {//如果是最后一个
end = contentLength-1;
}
new Thread(new DownloadRunnable(url, file, start, end)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}