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

HttpURLConnection获取网络数据工具类

2016-10-29 15:20 387 查看
/**
* 創建
* 创建人:陈坚润
* 时间:2016-10-29
* 功能:连接网络服务器,获取网上数据
* getHttpToByteArray是用來返回一個byte數組的,一般我是想用來獲取網上的圖片的
* getHttpToString是用來獲取網上數據最後以一個String類型的數據返回
*/

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.Buffer;
import java.util.stream.IntStream;

public class HttpUtil {

/**
* 功能:连接网络服务器,获取网上数据,我是用來獲取網上圖片的
* 参数:URL地址
* 返回:btye[]
*
*/
public static byte[] getHttpToByteArray(String urlPath){

try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
byte[] data = readStream(inputStream).toByteArray();
inputStream.close();
return data;
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 创建人:陈坚润
* 时间:2016-10-29
* 功能:连接网络服务器,获取网上数据
* 参数:URL地址
* 返回:string
*
*/
public static String getHttpToString(String urlPath){

try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setRequestProperty("Content-type", "text/html");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
return new String(readStream(inputStream).toByteArray(),"UTF-8");

}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

private static ByteArrayOutputStream readStream(InputStream inputStream){
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = inputStream.read(buffer))!= -1){
out.write(buffer,0,len);
}
out.close();
inputStream.close();
return out;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpURLConnection