java网络工具类

时间:2023-02-17 08:38:58
    public static String sendGet(String url, String ecoding) {
StringBuilder buffer = new StringBuilder();
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
InputStream inputStream = null;
HttpURLConnection httpUrlConn = null;
try {
URL req_url = new URL(url);
httpUrlConn = (HttpURLConnection) req_url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setConnectTimeout(10000);
httpUrlConn.setReadTimeout(10000);
httpUrlConn.setRequestMethod("GET");
// httpUrlConn.setRequestProperty("Accept", "image/png,image/*;q=0.8,*/*;q=0.5");
// httpUrlConn.setRequestProperty("Accept-Encoding", "gzip");
//httpUrlConn.setRequestProperty("Referer", "http://www.hao123.com/");
httpUrlConn.connect(); //发送请求
if (httpUrlConn.getResponseCode() == 200) {
// 将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, ecoding);
bufferedReader = new BufferedReader(inputStreamReader);
String str;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (httpUrlConn != null) {
httpUrlConn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer.toString();
}

public static byte[] download(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (conn.getResponseCode() == 200) {
byte[] buffer = new byte[8 * 1024];
int len;
int totalLen = conn.getContentLength();
int curLen = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
curLen += len;
int p = curLen * 100 / totalLen;
System.out.println("下载进度" + p + "%");
}
is.close();
conn.disconnect();
}
return baos.toByteArray();
}

public static void saveFile(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}