Java 后台 Http 请求,文件上传(支持多参数和文件同时请求)

发送请求工具类


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.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * http工具类
 * 
 * @author Jonathan_SU
 *
 */
public class HttpRequestUtil {

	private static Logger log = LoggerFactory.getLogger(HttpsRequestUtil.class);

	private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识
	private final static String PREFIX = "--";// 必须存在
	private final static String LINE_END = "\r\n";

	/**
	 * post方式请求服务器(http协议)
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            参数 如:id=1&data="";多个参数用&隔开,data的值可以是JSON格式字符串
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @throws IOException
	 */
	public String post(String url, String content) throws NoSuchAlgorithmException, KeyManagementException, IOException {
		URL console = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) console.openConnection();
		conn.setDoOutput(true);
		conn.addRequestProperty("connection", "Keep-Alive");
		conn.connect();

		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(content.getBytes("utf-8"));
		// 刷新、关闭
		out.flush();
		out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			if (outStream != null) {
				return new String(outStream.toByteArray(), "utf-8");
			}
		}
		return null;
	}

	/**
	 * POST Multipart Request
	 * 
	 * @Description:
	 * @param requestUrl
	 *            请求url
	 * @param requestText
	 *            请求参数
	 * @param localFilePath
	 *            请求上传的本地文件路径
	 * @return
	 * @throws Exception
	 */
	public String sendRequestWithFile(String requestUrl, Map<String, String> requestText, String localFilePath) throws Exception {
		HttpURLConnection conn = null;
		InputStream input = null;
		OutputStream os = null;
		BufferedReader br = null;
		StringBuffer buffer = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(1000 * 10); // 10秒 连接主机的超时时间(单位:毫秒)
			conn.setReadTimeout(1000 * 10); // 10秒 从主机读取数据的超时时间(单位:毫秒)

			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "*/*");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			conn.connect();

			// 往服务器端写内容 也就是发起http请求需要带的参数
			os = new DataOutputStream(conn.getOutputStream());
			// 请求参数部分
			writeParams(requestText, os);
			// 请求上传文件部分
			Map<String, MultipartFile> requestFile = new HashMap<String, MultipartFile>();
			File file = new File(localFilePath);
			FileInputStream fileInputStream = new FileInputStream(file);
			MultipartFile multipartFile = new MultipartFileDto(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
			requestFile.put("file", multipartFile);
			writeFile(requestFile, os);
			// 请求结束标志
			String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
			os.write(endTarget.getBytes());
			os.flush();

			// 读取服务器端返回的内容
			// System.out.println("======================响应体=========================");
			// System.out.println("ResponseCode:" + conn.getResponseCode() +
			// ",ResponseMessage:" + conn.getResponseMessage());
			if (conn.getResponseCode() == 200) {
				input = conn.getInputStream();
			} else {
				input = conn.getErrorStream();
			}

			br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
			buffer = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}
			// ......
			// System.out.println("返回报文:" + buffer.toString());

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new Exception(e);
		} finally {
			try {
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}

				if (os != null) {
					os.close();
					os = null;
				}

				if (br != null) {
					br.close();
					br = null;
				}
			} catch (IOException ex) {
				log.error(ex.getMessage(), ex);
				throw new Exception(ex);
			}
		}
		return buffer.toString();
	}

	/**
	 * 对post参数进行编码处理并写入数据流中
	 * 
	 * @throws Exception
	 * 
	 * @throws IOException
	 * 
	 * */
	private static void writeParams(Map<String, String> requestText, OutputStream os) throws Exception {
		try {
			String msg = "请求参数部分:\n";
			if (requestText == null || requestText.isEmpty()) {
				msg += "空";
			} else {
				StringBuilder requestParams = new StringBuilder();
				Set<Map.Entry<String, String>> set = requestText.entrySet();
				Iterator<Entry<String, String>> it = set.iterator();
				while (it.hasNext()) {
					Entry<String, String> entry = it.next();
					requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
					requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);
					requestParams.append("Content-Type: text/plain; charset=utf-8").append(LINE_END);
					requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
					requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
					requestParams.append(entry.getValue());
					requestParams.append(LINE_END);
				}
				os.write(requestParams.toString().getBytes());
				os.flush();

				msg += requestParams.toString();
			}

			// System.out.println(msg);
		} catch (Exception e) {
			log.error("writeParams failed", e);
			throw new Exception(e);
		}
	}

	/**
	 * 对post上传的文件进行编码处理并写入数据流中
	 * 
	 * @throws IOException
	 * 
	 * */
	private static void writeFile(Map<String, MultipartFile> requestFile, OutputStream os) throws Exception {
		InputStream is = null;
		try {
			String msg = "请求上传文件部分:\n";
			if (requestFile == null || requestFile.isEmpty()) {
				msg += "文件为空";
			} else {
				StringBuilder requestParams = new StringBuilder();
				Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet();
				Iterator<Entry<String, MultipartFile>> it = set.iterator();
				while (it.hasNext()) {
					Entry<String, MultipartFile> entry = it.next();
					if (entry.getValue() == null) {// 剔除value为空的键值对
						continue;
					}
					requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
					requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"; filename=\"").append(entry.getValue().getName())
							.append("\"").append(LINE_END);
					requestParams.append("Content-Type:").append(entry.getValue().getContentType()).append(LINE_END);
					requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
					requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容

					os.write(requestParams.toString().getBytes());
					os.write(entry.getValue().getBytes());

					os.write(LINE_END.getBytes());
					os.flush();

					msg += requestParams.toString();
				}
			}
			// System.out.println(msg);
		} catch (Exception e) {
			log.error("writeFile failed", e);
			throw new Exception(e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (Exception e) {
				log.error("writeFile FileInputStream close failed", e);
				throw new Exception(e);
			}
		}
	}

}


 封装文件所需类

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author Jonathan_SU
 *
 */
public class MultipartFileDto implements MultipartFile {
	private final String name;

	private String originalFilename;

	private String contentType;

	private final byte[] content;

	/**
	 * Create a new MultipartFileDto with the given content.
	 * 
	 * @param name
	 *            the name of the file
	 * @param content
	 *            the content of the file
	 */
	public MultipartFileDto(String name, byte[] content) {
		this(name, "", null, content);
	}

	/**
	 * Create a new MultipartFileDto with the given content.
	 * 
	 * @param name
	 *            the name of the file
	 * @param contentStream
	 *            the content of the file as stream
	 * @throws IOException
	 *             if reading from the stream failed
	 */
	public MultipartFileDto(String name, InputStream contentStream) throws IOException {
		this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));
	}

	/**
	 * Create a new MultipartFileDto with the given content.
	 * 
	 * @param name
	 *            the name of the file
	 * @param originalFilename
	 *            the original filename (as on the client's machine)
	 * @param contentType
	 *            the content type (if known)
	 * @param content
	 *            the content of the file
	 */
	public MultipartFileDto(String name, String originalFilename, String contentType, byte[] content) {
		this.name = name;
		this.originalFilename = (originalFilename != null ? originalFilename : "");
		this.contentType = contentType;
		this.content = (content != null ? content : new byte[0]);
	}

	/**
	 * Create a new MultipartFileDto with the given content.
	 * 
	 * @param name
	 *            the name of the file
	 * @param originalFilename
	 *            the original filename (as on the client's machine)
	 * @param contentType
	 *            the content type (if known)
	 * @param contentStream
	 *            the content of the file as stream
	 * @throws IOException
	 *             if reading from the stream failed
	 */
	public MultipartFileDto(String name, String originalFilename, String contentType, InputStream contentStream) throws IOException {

		this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public String getOriginalFilename() {
		return this.originalFilename;
	}

	@Override
	public String getContentType() {
		return this.contentType;
	}

	@Override
	public boolean isEmpty() {
		return (this.content.length == 0);
	}

	@Override
	public long getSize() {
		return this.content.length;
	}

	@Override
	public byte[] getBytes() throws IOException {
		return this.content;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(this.content);
	}

	@Override
	public void transferTo(File dest) throws IOException, IllegalStateException {
		FileCopyUtils.copy(this.content, dest);
	}
}

 https 方式 在方法体最前面加入如下代码即可:

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

接收端代码(文件的接收)

import java.io.File;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.core.Context;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@RestController
@RequestMapping(value = "/api")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServerController {

@POST
@RequestMapping(value = "/submitFile", produces = "application/json;charset=utf-8")
public ModelAndView submitFile(MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
		
        MultipartHttpServletRequest multipartRequest = WebUtils
				.getNativeRequest(request, MultipartHttpServletRequest.class);
	MultipartFile multipartfile = multipartRequest.getFile("file");
	    

			String fileName = request.getParameter("fileName");
			// 把文件写到本地服务器临时目录
			String localFilePath = System.getProperty("projectApi.root") + File.separator + "temp";
			File tempDiskFile = new File(localFilePath + File.separator + fileName);
			multipartfile.transferTo(tempDiskFile);
			
			System.out.println("---tempDiskFile-----" + tempDiskFile);
			
			if(!tempDiskFile.exists() || tempDiskFile.length() == 0) {
			    System.err.println("---文件提交失败,文件异常,文件大小为0 -----"); 
                            writeJSON(response, "{'code':'E','msg':'文件提交失败,文件异常,文件大小为0'}"));
                            return null;
			}
        writeJSON(response, "{'code':'S','msg':'文件提交成功'}"));
			
	return null;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值