使用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将是否续写设置为truebyte[] 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 * 1024System.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;}@Overridepublic 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();}}
}

Java中的Http连接相关推荐

  1. Java中使用Jedis连接Redis对SortedSet进行排序操作

    场景 Centos中Redis的下载编译与安装(超详细): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103967334 Re ...

  2. Java中使用Jedis连接Redis对Hash进行操作的常用命令

    场景 Centos中Redis的下载编译与安装(超详细): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103967334 Re ...

  3. Java中使用Jedis连接Redis对Set进行操作的常用命令

    场景 Centos中Redis的下载编译与安装(超详细): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103967334 Re ...

  4. Java中使用Jedis连接Redis对List进行操作的常用命令

    场景 Centos中Redis的下载编译与安装(超详细): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103967334 Re ...

  5. Java中使用Jedis连接Redis对String进行操作的常用命令

    场景 Centos中Redis的下载编译与安装(超详细): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103967334 Re ...

  6. Java中使用Jedis连接Redis对Key进行操作的常用命令

    场景 Java中使用Jedis连接池连接Redis数据库流程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/104914320 ...

  7. 在java中使用JDBC连接mysql数据库时的服务器时区值无法识别或表示多个时区的问题解决方案

    项目场景: 在java中使用JDBC连接mysql数据库时,报以下的错:Exception in thread "main" java.sql.SQLException: The ...

  8. java中class.forname连接mysql数据库_数据库链接与 Class.forName()用法详解

    主要功能 Class.forName(xxx.xx.xx)返回的是一个类 Class.forName(xxx.xx.xx)的作用是要求JVM查找并加载指定的类, 也就是说JVM会执行该类的静态代码段 ...

  9. java 菜单 分隔符_在Java中使用分隔符连接值列表最优雅的方法是什么?

    我从来没有找到一个整洁(呃)的方式来做以下事情. 说我有一个列表/数组的字符串. abc def ghi jkl 我想将它们连接成一个由逗号分隔的单个字符串,如下所示: abc,def,ghi,jkl ...

  10. java中常用的连接池_java数据库连接池

    编写标准的数据源(规范) Java为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口.这样应用程序可以方便的切换不同厂商的连接池! 常见的 ...

最新文章

  1. python基本数据类型之序列类型和映射类型
  2. android错误整理——模拟器无法连接网络
  3. cogs 610. 数对的个数
  4. Anaconda:包安装以XGBoost为例
  5. vue取通过key取value_vue怎么获取radio、checkbox选中的值
  6. [蓝桥杯2018初赛]方格计数-巧妙枚举,找规,数论
  7. LeetCode 1534. 统计好三元组
  8. oracle rman 检查坏块,Oracle中使用RMAN来检验坏块
  9. HTML5 css链接添加不同的样式
  10. CAS总结之Ticket篇
  11. nux下导入、导出mysql数据库命令
  12. QQ机器人{退出/回复设置/日志记录篇}
  13. 生鲜配送小程序源码_生鲜配送小程序系统功能开发介绍(附带源码)
  14. 【F28003x】 Enhanced Pulse Width Modulator (ePWM)
  15. 安科瑞AWT100-4G物联网通讯终端 无线通讯终端 数据传输单元
  16. 李嘉诚--理财--如何支配你的金钱
  17. 《数据密集型计算和模型》第二章大数据时代的计算机体系结构复习
  18. 一个基于EntityFrameworkCore+Lucene实现的全文搜索引擎库
  19. ABB高过载能力脉冲电流互感器
  20. 继“CP936”也失效之后重新自定义方法解决GDAL读取SHP乱码问题

热门文章

  1. ChromeDriver版本(最新v2.45)与Chrome版本(最新v72)支持关系以及下载地址
  2. html5手机摄像头相册批量,h5调用手机摄像头/相册(示例代码)
  3. 带电检测必要性_GIS的概念和定期局部放电检测的重要性
  4. Odoo的采购入库单、销售发货单整单被取消,或选择了不生成欠单后又想继续入库或发货,如何处理?
  5. 兄弟dcp9020cdn手册_兄弟Brother DCP-9020CDN 驱动
  6. 数电期末基础知识整理
  7. 前端实现Office在线预览 (一)
  8. Linux消息队列扩充上限,linux系统增加消息队列长度
  9. ps4插html屏幕不亮光,ps4连接显示器怎么老是黑屏
  10. java数据流编辑 kylo,Kylo 在个推信息流推荐引擎中的使用及扩展