以下代码用于将文件上传到服务器。
public static boolean uploadFile(String serverUrl, String filePath) {
boolean status = false;
try {
File file = new File(filePath);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(serverUrl);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
reqEntity.addPart(IShipdocsMobileConstants.CUSTOM_FILE_TAG, bin);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
status = true;
}
}
catch (Exception e) {
status = false;
}
return status;
}
当文件开始上传文件时没有连接但在文件已经开始上传时没有引发异常时抛出异常&一段时间后(可能在上传50%之后),连接丢失。
目前我正在使用WiFi和GPRS激活SIM上传。
需要将任何其他参数添加到上面的代码中才能获得异常。
欢迎任何提示/建议。