package org.moblie.train.zday09_json_MyUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class HttpURLConnHelper {
/**
* 作用:实现网络访问文件,将获取到数据储存在文件流中
*
* @param url
* :访问网络的url地址
* @return inputstream
*/
public static InputStream loadFileFromURL(String urlString) {
BufferedInputStream bis = null;
HttpURLConnection httpConn = null;
try {
URL urlObj = new URL(urlString);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(5000);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
return bis;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 作用:实现网络访问文件,将获取到的数据存在字节数组中
*
* @param url
* :访问网络的url地址
* @return byte[]
*/
public static byte[] loadByteFromURL(String url) {
HttpURLConnection httpConn = null;
BufferedInputStream bis = null;
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
httpConn.setConnectTimeout(5000);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
return streamToByte(bis);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 作用:实现网络访问文件,将获取到的数据保存在指定目录中
*
* @param url
* :访问网络的url地址
* @return byte[]
*/
public static boolean saveFileFromURL(String url, File destFile) {
HttpURLConnection httpConn = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(destFile));
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
httpConn.setConnectTimeout(5000);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
int c = 0;
byte[] buffer = new byte[8 * 1024];
while ((c = bis.read(buffer)) != -1) {
bos.write(buffer, 0, c);
bos.flush();
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
/**
* 作用:实现网络访问文件,先给服务器通过“POST”方式提交数据,再返回相应的数据
*
* @param url
* :访问网络的url地址
* @param params
* :访问url时,需要传递给服务器的参数。格式为:username=wangxiangjun&password=abcde&
* qq=32432432
* 为了防止传中文参数时出现编码问题。采用URLEncoder.encode()对含中文的字符串进行编码处理。
* 服务器端会自动对进行过编码的字符串进行decode()解码。
* @return byte[]
*/
public static byte[] doPostSubmit(String url, String params) {
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
HttpURLConnection httpConn = null;
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setConnectTimeout(5 * 1000);
if (params != null) {
byte[] data = params.getBytes();
bos = new BufferedOutputStream(httpConn.getOutputStream());
bos.write(data);
bos.flush();
}
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
return streamToByte(bis);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 网络访问,上传附件 五个参数: 1、String url:指定表单提交的url地址 2、Map<String, String>
* map:将上传控件之外的其他控件的数据信息存入map对象 3、String filePath:指定要上传到服务器的文件的客户端路径
* 4、byte[] body_data:获取到要上传的文件的输入流信息,通过ByteArrayOutputStream流转成byte[]
* 5、String charset:设置字符集
*/
public static String doPostSubmitBody(String url, Map<String, String> map,
String filePath, byte[] body_data, String charset) {
final String NEWLINE = "\r\n";
final String PREFIX = "--";
final String BOUNDARY = "#";
HttpURLConnection httpConn = null;
BufferedInputStream bis = null;
DataOutputStream dos = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setUseCaches(false);
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpConn.setRequestProperty("Cache-Control", "no-cache");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
httpConn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
httpConn.connect();
dos = new DataOutputStream(httpConn.getOutputStream());
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = map.get(key);
dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"" + key + "\"" + NEWLINE);
dos.writeBytes(NEWLINE);
dos.writeBytes(URLEncoder.encode(value.toString(), charset));
dos.writeBytes(NEWLINE);
}
}
if (body_data != null && body_data.length > 0) {
dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
String fileName = filePath.substring(filePath
.lastIndexOf(File.separatorChar) + 1);
dos.writeBytes("Content-Disposition: form-data; " + "name=\""
+ "uploadFile" + "\"" + "; filename=\"" + fileName
+ "\"" + NEWLINE);
dos.writeBytes(NEWLINE);
dos.write(body_data);
dos.writeBytes(NEWLINE);
}
dos.writeBytes(PREFIX + BOUNDARY + PREFIX + NEWLINE);
dos.flush();
byte[] buffer = new byte[8 * 1024];
int c = 0;
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
}
return new String(baos.toByteArray(), charset);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
if (bis != null) {
bis.close();
}
if (baos != null) {
baos.close();
}
httpConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] streamToByte(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c = 0;
byte[] buffer = new byte[8 * 1024];
try {
while ((c = is.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}