获取网络下载请求工具类

来源:互联网 发布:四川大学网络教育官网 编辑:程序博客网 时间:2024/06/06 06:32

网络下载数据

<span style="font-family:Comic Sans MS;font-size:18px;">package com.example.week2_day3_downloadjson.utils;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;//获取网络资源public class Utils {public static String getJson(String path){ByteArrayOutputStream out=new ByteArrayOutputStream();URL url;String json="";//接收json数据try {url=new URL(path);HttpURLConnection connection=(HttpURLConnection) url.openConnection();//打开网络连接connection.setReadTimeout(5000);//设置连接请求时间connection.setDoInput(true);//设置连接connection.connect();//连接if(connection.getResponseCode()==200){InputStream input = connection.getInputStream();byte[] buffer=new byte[1024];int temp=0;while ((temp=input.read(buffer))!=-1) {out.write(buffer, 0, temp);out.flush();}}return out.toString();} catch (Exception e) {e.printStackTrace();}return json;}}</span>


0 0
原创粉丝点击