对于上传文件,您可以创建一个线程/异步,例如: public class HttpFileUploader {
private static final String TAG = "HttpFileUploader";
private URL connectURL;
private Map<String, String> params;
// private String responseString;
private String fileName, photoParamName;
// private byte[] dataToServer;
private FileInputStream fileInputStream = null;
String responce = "";
public HttpFileUploader(Map<String, String> params, String photoParamName,
String fileName, String urlString) {
try {
System.out.println(urlString);
connectURL = new URL(urlString);
} catch (Exception ex) {
Log.i(TAG, "MALFORMATED URL");
}
this.params = params;
this.fileName = fileName;
this.photoParamName = photoParamName;
}
/**
* Starts uploading.
*
* @throws FileNotFoundException
*/
public String doStart() throws FileNotFoundException {
fileInputStream = new FileInputStream(new File(fileName));
thirdTry();
return responce;
}
private void thirdTry() {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "**lx90l39slks02klsdfaksd2***";
try {
// ------------------ CLIENT REQUEST
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) connectURL
.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
// conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// add the params to the form data
if (params != null) {
for (Entry<String, String> entry : params.entrySet()) {
// Log.d(TAG, "submitting param "
// + entry.getKey() + " : " + entry.getValue());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(entry.getValue());
dos.writeBytes(lineEnd);
}
}
// Log.d(TAG, "submitting image " + photoParamName
// + " : " + fileName);
// add image to the form data
dos.writeBytes(twoHyphens + boundary + lineEnd);
if (photoParamName == null)
photoParamName = "photo";
dos.writeBytes("Content-Disposition: form-data;name=\""
+ photoParamName + "\";filename=\"" + photoParamName + "\""
+ lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
// upload image
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.d(TAG, "File (" + fileName + ") is written");
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
responce = s;
Log.i(TAG, "Response =" + s);
dos.close();
} catch (MalformedURLException ex) {
Log.e(TAG, "error URL: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e(TAG, "error IO: " + ioe.getMessage(), ioe);
}
}
}
上传成功后,您的 web api 必须返回成功响应,如果它没有完成/异常,则在通过检查网络连接重试几次后上传时出现异常。您还可以启动计时器以重做任务。