本文介绍了使用HttpURLConnection将文件与其他表单数据一起发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将文件连同其他参数一起发布到我的API中.
Im trying to POST a file to an API of mine along with other parameters.
例如. POST/媒体使用参数
Eg. POST /mediawith the parameters
filename ='test.png'
filename = 'test.png'
file =-实际文件-
file = -the-actual-file-
我可以使用Postman(使用表单数据)成功完成此操作,因此api方面的工作都很好.
I can do this successfully with Postman (using form-data), so the api side of things are fine.
这是我使用HttpURLConnection的android代码:
Here is my android code using HttpURLConnection:
nameValuePairs.add(new BasicNameValuePair("filename", "test.png"));
URL object = new URL(url);
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
String auth = username+":"+password;
byte[] data = auth.getBytes();
String encodeAuth = "Basic " + Base64.encodeToString(data, Base64.DEFAULT);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", encodeAuth);
connection.setRequestProperty("Accept", ACCEPT);
connection.setRequestMethod("POST");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
writer = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.write("&file=" + "image.jpg");
writer.write
File file = getFile(item);
if (file == null) {
Log.e("uploadFile", "Source File not exist " );
} else {
addFilePart("file", file);
}
}
writer.flush();
writer.close();
dataOutputStream.close();
connection.connect();
推荐答案
Android分段上传.
Android multipart upload.
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (200 != connection.getResponseCode()) {
throw new CustomException("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
logger.error(e);
throw new CustomException(e);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
呼叫代码:
//setup params
Map<String, String> params = new HashMap<String, String>(2);
params.put("foo", hash);
params.put("bar", caption);
String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4");
//next parse result string
引用链接 https://stackoverflow.com/a/26145565/1143026
这篇关于使用HttpURLConnection将文件与其他表单数据一起发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!