您的位置:首页 > 理论基础 > 计算机网络

获取网络下载请求工具类

2015-09-22 17:08 288 查看
网络下载数据

<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: