300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > HttpURLConnection模拟form表单提交文件

HttpURLConnection模拟form表单提交文件

时间:2022-08-26 07:48:50

相关推荐

HttpURLConnection模拟form表单提交文件

独角兽企业重金招聘Python工程师标准>>>

文件上传方法

/**

*

* @param urlStr url地址

* @param textMap 附带信息

* @param fileMap 文件列表

* @return 返回json的报文 如果失败,则为空

*/

public static String postFileByForm(String urlStr, Map<String, String> textMap,

Map<String, String> fileMap){

String res = "";

HttpURLConnection conn = null;

String BOUNDARY = "---------------------------"; //boundary就是request头和上传文件内容的分隔符

try {

URL url = new URL(urlStr);

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setReadTimeout(30000);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("User-Agent",

"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

conn.setRequestProperty("Content-Type",

"multipart/form-data; boundary=" + BOUNDARY);

OutputStream out = new DataOutputStream(conn.getOutputStream());

// text

if (textMap != null) {

StringBuffer strBuf = new StringBuffer();

Iterator iter = textMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

String inputName = (String) entry.getKey();

String inputValue = (String) entry.getValue();

if (inputValue == null) {

continue;

}

strBuf.append("\r\n").append("--").append(BOUNDARY).append(

"\r\n");

strBuf.append("Content-Disposition: form-data; name=\""

+ inputName + "\"\r\n\r\n");

strBuf.append(inputValue);

}

out.write(strBuf.toString().getBytes());

}

// file

if (fileMap != null) {

Iterator iter = fileMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

String inputName = (String) entry.getKey();

String inputValue = (String) entry.getValue();

if (inputValue == null) {

continue;

}

File file = new File(inputValue);

String filename = file.getName();

String contentType = new MimetypesFileTypeMap()

.getContentType(file);

if (contentType == null || contentType.equals("")) {

contentType = "application/octet-stream";

}

StringBuffer strBuf = new StringBuffer();

strBuf.append("\r\n").append("--").append(BOUNDARY).append(

"\r\n");

strBuf.append("Content-Disposition: form-data; name=\""

+ inputName + "\"; filename=\"" + filename

+ "\"\r\n");

strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

out.write(strBuf.toString().getBytes());

DataInputStream in = new DataInputStream(

new FileInputStream(file));

int bytes = 0;

byte[] bufferOut = new byte[1024];

while ((bytes = in.read(bufferOut)) != -1) {

out.write(bufferOut, 0, bytes);

}

in.close();

}

}

byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();

out.write(endData);

out.flush();

out.close();

// 读取返回数据

StringBuffer strBuf = new StringBuffer();

BufferedReader reader = new BufferedReader(new InputStreamReader(

conn.getInputStream()));

String line = null;

while ((line = reader.readLine()) != null) {

strBuf.append(line).append("\n");

}

res = strBuf.toString();

reader.close();

reader = null;

} catch (Exception e) {

//日志处理

res = "";

} finally {

if (conn != null) {

conn.disconnect();

conn = null;

}

}

return res;

}

调用测试代码

Map<String, String> textList = new HashMap<String, String>();

Map<String, String> fileList = new HashMap<String, String>();

textList.put("merchantId", "1");

textList.put("customerId", "2");

textList.put("fileType", "02");

textList.put("fileName", "121.gif");

fileList.put("file", "E://test//121.gif");

String s = postFileByForm("/paygate/uploadImage.json", textList, fileList);

System.out.println("result is:"+s);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。