JFianl通过httpurlconnection 进行文件上传出错


httpurlconnection 上传文件后台报错。

image.png

这里转化不过去?应该怎么搞?波总?




下面是部分httpurlconnection代码

public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {

String res = "";

HttpURLConnection conn = null;

String BOUNDARY = "---------------------------123821742118716"; //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<Map.Entry<String, String>> iter = textMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry<String, String> 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<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry<String, String> 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();

MagicMatch match = Magic.getMagicMatch(file, false, true);

String contentType = match.getMimeType();


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");


评论区

热门反馈

扫码入社