包结构
|---src
|---log4j-1.2.17.jar
|---slf4j-log4j12-1.7.5.jar
|---lib
|---\com\zy\demo
|---DoTest.java
|---HttpPostUtil.java
|---NetUtils.java
代码
DoTest.java
package com.zy.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.Test;
public class DoTest {
@SuppressWarnings("static-access")
public void test() throws IOException{
NetUtils demo=new NetUtils();
InputStream inputStream = demo.fileNetDownload("http://s4.51cto.com/wyfs02/M00/87/DF/wKioL1fjxXeySkcbAAAXTyCeiFM428.jpg-wh_651x-s_4234295533.jpg");
// InputStream inputStream = demo.fileDownload("http://music.baidu.com/pc/download//BaiduMusic-17011816.exe");
UUID key=UUID.randomUUID();
OutputStream outputStream = new FileOutputStream("D:\\测试\\"+key+".jpeg");
byte[] mByte = new byte[1024*1024*3];
int num = 0;
while ((num = inputStream.read(mByte)) != -1) {
outputStream.write(mByte, 0, num);
}
outputStream.close();
inputStream.close();
}
public void post() {
Map< String, String> map=new HashMap<>();
map.put("name", "NAME");
//正常
// String post = NetUtils.post("http://192.168.0.121:8090/YouGuoApp/SetUp/getNewApkVersion.do",map);
//正常
// String post = NetUtils.post("http://192.168.0.121:8090/YouGuoApp/SetUp/getNewApkVersion.do",NetUtils.changeMapToBody(map));
//参数过去了
String post = NetUtils.sendGet("http://192.168.0.121:8090/YouGuoApp/SetUp/getNewApkVersion.do",NetUtils.changeMapToBody(map));
//正常
// String post = NetUtils.get("http://192.168.0.121:8090/YouGuoApp/SetUp/getNewApkVersion.do?name=7898456");
System.out.println(post);
}
@Test
public void upload(){
File file = new File("D:\\测试\\14465a72-cad3-40e5-a2ee-fabc147e92a1.jpeg");
// String fileLocalUpdate =HttpConnectionUtil.uploadFile("http://192.168.0.121:8090/YouGuoApp/file/uploadOneFile.do",new String[] { "D:\\测试\\14465a72-cad3-40e5-a2ee-fabc147e92a1.jpeg"});
// String fileLocalUpdate = NetUtils.fileLocalUpdate("D:\\测试\\14465a72-cad3-40e5-a2ee-fabc147e92a1.jpeg", "http://192.168.0.121:8090/YouGuoApp/file/uploadOneFile.do");
System.out.println(file.getName());
}
}
HttpPostUtil.java
package com.zy.demo;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class HttpPostUtil {
URL url;
HttpURLConnection conn;
String boundary = "--------httppost123";
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();
DataOutputStream ds;
public HttpPostUtil(String url) throws Exception {
this.url = new URL(url);
}
//重新设置要请求的服务器地址,即上传文件的地址。
public void setUrl(String url) throws Exception {
this.url = new URL(url);
}
//增加一个普通字符串数据到form表单数据中
public void addTextParameter(String name, String value) {
textParams.put(name, value);
}
//增加一个文件到form表单数据中
public void addFileParameter(String name, File value) {
fileparams.put(name, value);
}
// 清空所有已添加的form表单数据
public void clearAllParameters() {
textParams.clear();
fileparams.clear();
}
// 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public byte[] send() throws Exception {
initConnection();
try {
conn.connect();
} catch (SocketTimeoutException e) {
// something
throw new RuntimeException();
}
ds = new DataOutputStream(conn.getOutputStream());
writeFileParams();
writeStringParams();
paramsEnd();
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
return out.toByteArray();
}
//文件上传的connection的一些必须设置
private void initConnection() throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000); //连接超时为10秒
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
}
//普通字符串数据
private void writeStringParams() throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n");
ds.writeBytes("\r\n");
ds.writeBytes(encode(value) + "\r\n");
}
}
//文件数据
private void writeFileParams() throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = fileparams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + encode(value.getName()) + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
ds.writeBytes("\r\n");
}
}
//获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
private String getContentType(File f) throws Exception {
// return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(f);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写
}
//把文件转换成字节数组
private byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
//添加结尾数据
private void paramsEnd() throws Exception {
ds.writeBytes("--" + boundary + "--" + "\r\n");
ds.writeBytes("\r\n");
}
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
public static void main(String[] args) throws Exception {
HttpPostUtil u = new HttpPostUtil("http://192.168.0.121:8090/YouGuoApp/file/uploadOneFile.do");
u.addFileParameter("img", new File("D:\\测试\\14465a72-cad3-40e5-a2ee-fabc147e92a1.jpeg"));
u.addTextParameter("text", "lalalalaal");
byte[] b = u.send();
String result = new String(b);
System.out.println(result);
}
}
NetUtils.java
package com.zy.demo;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.log4j.Logger;
public class NetUtils {
static String boundary = "--------httppost123";
private static Logger logger = Logger.getLogger(NetUtils.class);
/**
* 将map请求参数格式化
*
* @param ParamsMap
* 请求的参数
* @return 格式化后的参数
*/
public static String changeMapToBody(Map<String, String> ParamsMap) {
StringBuffer params = new StringBuffer();
// 组织请求参数
Iterator<?> it = ParamsMap.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry element = (Map.Entry) it.next();
params.append(element.getKey());
params.append("=");
params.append(element.getValue());
params.append("&");
}
if (params.length() > 0) {
params.deleteCharAt(params.length() - 1);
}
return params.toString();
}
/**
* post发出网络请求 post请求
*
* @param url
* 功能和操作
* @param body
* 要post的数据 String body = "accountSid=" + ACCOUNT_SID + "&to=" +
* tel + "&templateid=" + templateid + "¶m=" + param+
* createCommonParam();
* @return 请求返回的数据
* @throws IOException
*/
public static String sendPost(String url, String body) {
String result = "";
try {
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置连接参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
// 提交数据
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 读取返回数据
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
String line;
boolean firstLine = true; // 读第一行不加换行符
while ((line = in.readLine()) != null) {
if (firstLine) {
firstLine = false;
} else {
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e) {
e.printStackTrace();
// 异常返回空
return result;
}
return result;
}
/**
* post发出网络请求 post请求
*
* @param requestUrl
* 请求地址
* @param requestParamsMap
* 请求参数map
* @return 请求返回的数据
*/
public static String sendPost(String requestUrl,
Map<String, String> requestParamsMap) {
PrintWriter printWriter = null;
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader = null;
StringBuffer params = new StringBuffer();
StringBuffer responseResult = new StringBuffer();
// 组织请求参数
Iterator<?> it = requestParamsMap.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry element = (Map.Entry) it.next();
params.append(element.getKey());
params.append("=");
params.append(element.getValue());
params.append("&");
}
if (params.length() > 0) {
params.deleteCharAt(params.length() - 1);
}
try {
URL realUrl = new URL(requestUrl);
// 打开和URL之间的连接
httpURLConnection = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(params.length()));
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("content-type",
"application/x-www-form-urlencoded;charset=UTF-8");
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");// 设置URL请求方法
httpURLConnection.setConnectTimeout(50000);// 设置连接超时
// 如果在建立连接之前超时期满,则会引发一个
// java.net.SocketTimeoutException。超时时间为零表示无穷大超时。
httpURLConnection.setReadTimeout(50000);// 设置读取超时
// 如果在数据可读取之前超时期满,则会引发一个
// java.net.SocketTimeoutException。超时时间为零表示无穷大超时。
// 获取URLConnection对象对应的输出流
printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(params.toString());
// flush输出流的缓冲
printWriter.flush();
// 根据ResponseCode判断连接是否成功
int responseCode = httpURLConnection.getResponseCode();
if (responseCode != 200) {
logger.debug("发送请求错误!" + responseCode);
return "发送请求错误!" + responseCode;
} else {
logger.debug("发送请求成功!");
System.out.println("发送请求成功!");
}
// 定义BufferedReader输入流来读取URL的ResponseData
bufferedReader = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseResult.append(line);
}
} catch (Exception e) {
logger.debug("发送请求异常!" + e);
} finally {
httpURLConnection.disconnect();
try {
if (printWriter != null) {
printWriter.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return responseResult.toString();
}
/**
* get发出网络请求 get请求
*
* @param url
* 功能和操作
* @param map
* 请求的map
* @return 请求返回的数据
*/
public static String sendGet(String netPath, Map<String, String> map) {
String body = changeMapToBody(map);
netPath = netPath + "?" + body;
String result = sendGet(netPath);
return result;
}
/**
* get发出网络请求 get请求
*
* @param url
* 功能和操作
* @param body
* 要get的数据 String body = "accountSid=" + ACCOUNT_SID + "&to=" +
* tel + "&templateid=" + templateid + "¶m=" + param+
* createCommonParam();
* @return 请求返回的数据
*/
public static String sendGet(String netPath, String body) {
netPath = netPath + "?" + body;
String result = sendGet(netPath);
return result;
}
/**
* get 从网络获取数据
*
* @param path
* @return 请求返回的数据
*/
public static String sendGet(String path) {
try {
URL url = new URL(path.trim());
// 打开连接
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (200 == urlConnection.getResponseCode()) {
// 得到输入流
InputStream is = urlConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = is.read(buffer))) {
baos.write(buffer, 0, len);
baos.flush();
}
return baos.toString("utf-8");
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}
/**
* 从网络下载文件
*
* @param netPath
* 文件的网络地址
* @return InputStream io输入流
*/
public static InputStream fileNetDownload(String netPath) {
URL url = null;
try {
url = new URL(netPath);
} catch (MalformedURLException e) {
logger.debug("网络路径有误");
// 网络路径有误
return null;
}
URLConnection con = null;
try {
con = url.openConnection();
} catch (IOException e) {
logger.debug("网络路径有误");
// 网络路径有误对象为空
return null;
}
con.setConnectTimeout(1000);
InputStream inputStream = null;
try {
inputStream = con.getInputStream();
} catch (IOException e) {
logger.debug("网络路径有误");
// 网络路径有误对象为空
return null;
}
return inputStream;
}
/**
* 网络文件上传
* @param textParams参数的map(上传参数的key, 上传参数的值)
* @param fileparams(Spring上传取值的键, inputStream)
* @param filename(Spring上传取值的键, 文件的名称加后缀)
* @param netToPath (上传的地址)
* @return 对方返回的结果
* @throws Exception
*/
public static String inputStreamAndParamsUpload(
Map<String, String> textParams,
Map<String, InputStream> fileparams, Map<String, String> filename,
String netToPath) throws Exception {
String result = "";
try {
HttpURLConnection conn = initConnection(netToPath);
conn.connect();// 建立连接
DataOutputStream dataOutputStream = new DataOutputStream(
conn.getOutputStream());
// 如果参数map不为空并且size大于0则填写参数
if (fileparams != null && fileparams.size() > 0) {
// 填写文件file
writeFileParams(dataOutputStream, fileparams, filename);
}
// 如果参数map不为空并且size大于0则填写参数
if (textParams != null && textParams.size() > 0) {
// 填写参数map
writeStringParams(dataOutputStream, textParams);
}
paramsEnd(dataOutputStream);
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
result = new String(out.toByteArray());
} catch (Exception e) {
logger.debug("上传失败");
return null;
}
return result;
}
/**
* 本地文件和参数上传 如果文件map为空或者size为0则则默认不传, 如果参数map为空或者size为0则则默认不传,
*
* @param textParams
* 参数的map(上传参数的key, 上传参数的值)
* @param fileparams
* 文件路径的(Spring上传取值的键, 本地文件的路径)
* @param netToPath
* @return
*/
public static String fileAndParamsUpload(Map<String, String> textParams,
Map<String, String> fileparams, String netToPath) {
String result = "";
try {
HttpURLConnection conn;
conn = initConnection(netToPath);
conn.connect();// 建立连接
DataOutputStream dataOutputStream = new DataOutputStream(
conn.getOutputStream());
// 如果参数map不为空并且size大于0则填写参数
if (fileparams != null && fileparams.size() > 0) {
// 填写文件file
writeFileParams(dataOutputStream, fileparams);
}
// 如果参数map不为空并且size大于0则填写参数
if (textParams != null && textParams.size() > 0) {
// 填写参数map
writeStringParams(dataOutputStream, textParams);
}
paramsEnd(dataOutputStream);
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
result = new String(out.toByteArray());
} catch (Exception e) {
logger.debug("上传失败");
return null;
}
return result;
}
/**
* 填写上传参数数据
*
* @param dataOutputStream
* @throws Exception
*/
private static void writeStringParams(DataOutputStream dataOutputStream,
Map<String, String> textParams) throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
dataOutputStream.writeBytes("--" + boundary + "\r\n");
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ name + "\"\r\n");
dataOutputStream.writeBytes("\r\n");
dataOutputStream.writeBytes(encode(value) + "\r\n");
}
}
/**
* 填写上传文件数据
*
* @param dataOutputStream
* @throws Exception
* @throws IOException
*/
private static void writeFileParams(DataOutputStream dataOutputStream,
Map<String, String> fileparams) throws IOException, Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = new File(fileparams.get(name));
dataOutputStream.writeBytes("--" + boundary + "\r\n");
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ name + "\"; filename=\""
+ encode(value.getName()) + "\"\r\n");
dataOutputStream.writeBytes("Content-Type: "
+ getContentType(value) + "\r\n");
dataOutputStream.writeBytes("\r\n");
FileInputStream fileInputStream = new FileInputStream(value);
dataOutputStream.write(getBytes(fileInputStream));
dataOutputStream.writeBytes("\r\n");
}
}
/**
* 填写上传文件数据
*
* @param dataOutputStream
* @throws Exception
* @throws IOException
*/
private static void writeFileParams(DataOutputStream dataOutputStream,
Map<String, InputStream> fileparams, Map<String, String> filename)
throws IOException, Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
InputStream value = fileparams.get(name);
dataOutputStream.writeBytes("--" + boundary + "\r\n");
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ name + "\"; filename=\""
+ encode(filename.get(name)) + "\"\r\n");
dataOutputStream.writeBytes("Content-Type: "
+ getContentType(value) + "\r\n");
dataOutputStream.writeBytes("\r\n");
dataOutputStream.write(getBytes(value));
dataOutputStream.writeBytes("\r\n");
}
}
/**
* 初始化HttpURLConnection对象
*
* @param netToPath
* @return
* @throws IOException
*/
private static HttpURLConnection initConnection(String netToPath)
throws IOException {
// 统一资源
HttpURLConnection conn = null;
URL url = new URL(netToPath);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000); // 连接超时为10秒
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
return conn;
}
/**
* 对文字进行编码
*
* @param value
* @return
* @throws Exception
*/
private static String encode(String value) throws Exception {
return URLEncoder.encode(value, "UTF-8");
}
/**
* 获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
*
* @param f
* @return
* @throws Exception
*/
private static String getContentType(InputStream in) throws Exception {
// return "application/octet-stream"; //
// 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(in);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();// 将FormatName返回的值转换成小写,默认为大写
}
/**
* 获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
*
* @param f
* @return
* @throws Exception
*/
private static String getContentType(File f) throws Exception {
// return "application/octet-stream"; //
// 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(f);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();// 将FormatName返回的值转换成小写,默认为大写
}
/**
* 把文件转换成字节数组
*
* @param FileInputStream
* @return
* @throws Exception
*/
private static byte[] getBytes(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
/**
* 添加结尾数据
*
* @param dataOutputStream
* @throws IOException
*/
private static void paramsEnd(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeBytes("--" + boundary + "--" + "\r\n");
dataOutputStream.writeBytes("\r\n");
}
}
网友评论