HttpURLConnection(File) POST请求发送参数和上传文件

package com.face;

import java.io.BufferedReader;
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.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	private static Logger log = LoggerFactory.getLogger(HttpUtil.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 Multipart Request
	 *  @Description: 
	 *  @param requestUrl 请求url
	 *  @param requestText 请求参数(字符串键值对map)
	 *  @param requestFile 请求上传的文件(File)
	 *  @return
	 *  @throws Exception
	 */
	public static String sendRequest(String requestUrl,
			Map<String, String> requestText, Map<String, File> requestFile) 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);
			conn.setReadTimeout(1000 * 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);
			// 请求上传文件部分
			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, File> 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, File>> set = requestFile.entrySet();
				Iterator<Entry<String, File>> it = set.iterator();
				while (it.hasNext()) {
					Entry<String, File> entry = it.next();
					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(getContentType(entry.getValue()))
							.append(LINE_END);
					requestParams.append("Content-Transfer-Encoding: 8bit").append(
							LINE_END);
					requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容

					os.write(requestParams.toString().getBytes());
					
					is = new FileInputStream(entry.getValue());
					
					byte[] buffer = new byte[1024*1024];
					int len = 0;
					while ((len = is.read(buffer)) != -1) {
						os.write(buffer, 0, len);
					}
					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);
			}
		}
	}

	/**
	 * ContentType
	 * 
	 * @Description:
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String getContentType(File file) throws Exception{
		String streamContentType = "application/octet-stream";
		String imageContentType = "";
		ImageInputStream image = null;
		try {
			image = ImageIO.createImageInputStream(file);
			if (image == null) {
				return streamContentType;
			}
			Iterator<ImageReader> it = ImageIO.getImageReaders(image);
			if (it.hasNext()) {
				imageContentType = "image/" + it.next().getFormatName();
				return imageContentType;
			}
		} catch (IOException e) {
			log.error("method getContentType failed", e);
			throw new Exception(e);
		} finally {
			try{
				if (image != null) {
					image.close();
				}
			}catch(IOException e){
				log.error("ImageInputStream close failed", e);;
				throw new Exception(e);
			}
			
		}
		return streamContentType;
	}

    public static void main(String[] args) throws Exception {
		String requestURL = "https://api.megvii.com/faceid/v3/ocrbankcard";
		HttpUtil httpReuqest = new HttpUtil();
		
		Map<String,String> requestText = new HashMap<String,String>();
		requestText.put("api_key", "xxxxxxxxxxxxxxxxx");
		requestText.put("api_secret", "xxxxxxxxxxxxxxxxx");
		Map<String,File> requestFile = new HashMap<String,File>();
		requestFile.put("image", new         
              File("C:\\Users\\Administrator\\Desktop\\pic\\face.JPG"));
		httpReuqest.sendRequest(requestURL, requestText, requestFile);
	}
}

 

在 Java 中发送 POST 请求并携带文件和参数,你可以使用 `java.net.HttpURLConnection` 类来实现。下面是一个示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploadExample { public static void main(String[] args) throws IOException { String url = "http://example.com/upload"; // 请求的URL String filePath = "/path/to/file"; // 文件路径 String paramName = "file"; // 文件参数名 String paramName2 = "param1"; // 其他参数名 String paramValue2 = "value1"; // 其他参数File file = new File(filePath); URL requestUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); connection.setDoOutput(true); // 设置请求头部信息 connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); try (OutputStream outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream))) { // 写入文件参数 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + file.getName() + "\"\r\n") .append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + "\r\n") .append("\r\n") .flush(); // 写入文件内容 try (InputStream inputStream = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } // 写入其他参数 writer.append("\r\n") .append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName2 + "\"\r\n") .append("\r\n") .append(paramValue2) .append("\r\n") .flush(); // 结束标记 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n").flush(); } // 发送请求并获取响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } System.out.println("Response: " + response.toString()); } } } ``` 在上面的示例代码中,我们首先创建了一个 `HttpURLConnection` 对象,并设置请求方法为 POST,然后设置请求头部信息。接下来,我们使用输出流向服务器写入请求体内容,首先是文件参数,然后是文件内容,最后是其他参数发送请求后,我们可以获取响应的状态码和响应内容。 请注意,示例中的边界字符串 `"----WebKitFormBoundary7MA4YWxkTrZu0gW"` 只是一个示例,请根据实际情况修改该字符串。 希望这可以帮助到你!
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值