2

以下代码用于将文件上传到服务器。

        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 卡进行上传。

需要添加到上述代码中以获取异常的任何其他参数。

欢迎任何提示/建议。

4

0 回答 0