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
requestText, Map 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 requestText,
OutputStream os) throws Exception {
String msg = "请求参数部分:\n";
if (requestText == null || requestText.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set> set = requestText.entrySet();
Iterator> it = set.iterator();
while (it.hasNext()) {
Entry 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 requestFile,
OutputStream os) throws Exception {
InputStream is = null;
String msg = "请求上传文件部分:\n";
if (requestFile == null || requestFile.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set> set = requestFile.entrySet();
Iterator> it = set.iterator();
while (it.hasNext()) {
Entry 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{
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 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 {
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 requestText = new HashMap();
requestText.put("api_key", "xxxxxxxxxxxxxxxxx");
requestText.put("api_secret", "xxxxxxxxxxxxxxxxx");
Map requestFile = new HashMap();
requestFile.put("image", new
File("C:\\Users\\Administrator\\Desktop\\pic\\face.JPG"));
httpReuqest.sendRequest(requestURL, requestText, requestFile);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnec...
通过
HttpURLConnection
链接
上传文件
和
参数
,核心代码及操作步骤
public static String upload
File
(String url, Map<String, String> params,
File
file
) {
// 换行,或者说是回车
//final String newLine = "\r\n";
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.
File
;
import java.io.
File
InputStream;
import java.io.InputS...
从普通Web页面
上传文件
很简单,只需要在form标签叫上enctype=”multipart/form-data”即可,剩余工作便都交给浏览器去完成数据收集并
发送
Http
请求
。但是如果没有页面的话要怎么
上传文件
呢?
由于脱离了浏览器的环境,我们就要自己去完成数据的收集并
发送
请求
,所以就很麻烦了。首先我们来写个JSP页面并看看浏览器发出的Http
请求
是什么样的
文章目录一,
Post
请求
一,
Post
文件上传带
参数
一,
Post
请求
平时都是用第三方框架去网络
请求
,文件上传的,由于某种原因,现在使用原始
httpURLConnection
上传文件
public byte[] getToken(String baseUrl, String userName, String appId, String authToken) {
//
参数
判空...
在页面里实现
上传文件
不是什么难事,写个form,加上enctype = "multipart/form-data",在写个接收的就可以了,没什么难的,如果要用java.net.
HttpURLConnection
来实现文件上传,还真有点搞头.:-)
1.先写个servlet把接收到的 HTTP 信息保存在一个文件中, 看一下 form 表单到底封装了什么样的信息。
Java代码
当使用
HttpURLConnection
上传文件
时,需要设置
请求
方法为
POST
,并且在
请求
头中添加 Content-Type 和 Content-Disposition 字段,指定
上传文件
的类型和文件名。同时,需要在
请求
体中添加表单数据和文件内容。以下是一个示例代码:
URL url = new URL("http://example.com/upload");
HttpURLConnection
conn = (
HttpURLConnection
) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("
POST
");
String boundary = "*****"; // 自定义边界字符串
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream outputStream = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
// 添加表单数据
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"username\"").append("\r\n");
writer.append("\r\n");
writer.append("john").append("\r\n");
writer.flush();
// 添加文件内容
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"
file
\";
file
name=\"example.txt\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
writer.flush();
File
s.copy(Paths.get("example.txt"), outputStream);
outputStream.flush();
// 结束
请求
writer.append("\r\n").append("--" + boundary + "--").append("\r\n");
writer.close();
//
发送
请求
并读取响应
int statusCode = conn.getResponseCode();
if (statusCode ==
HttpURLConnection
.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// 处理响应数据
其中,boundary 字符串需要自定义,用于分隔不同的表单项。在添加表单数据和文件内容时,需要按照指定格式添加,并且在添加文件内容时需要使用 `
File
s.copy` 方法将文件内容写入到输出流中。最后,要记得关闭输出流和输入流,并根据响应状态码来处理响应数据。
wangshukaicode:
Java 搭建srs流媒体服务器,并使用ffmpeg推流
没有毛病:
Java 搭建srs流媒体服务器,并使用ffmpeg推流
业界小菜鸟: