如何在android httpUrlConnection中实现进度条

时间:2016-02-24 07:04:25

标签: android httpurlconnection android-progressbar

我正在使用额外的帖子数据上传多个文件,我想添加进度条, 我添加了一些代码,但是它不能正常工作,只有在从文件中检索数据时才计算,而不是在向服务器发送数据时...

如何实际写入服务器的字节?

感谢名单..

这是我的代码

package file.share.com.fileshare.helper;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class FileUploader {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private Context context;
private String android_id;
int second_prog=0,buffer_size=102400;//4096
Progress progress=new Progress(){@Override public void onUpload(long uploaded,long total,int second){}};
public FileUploader(String requestURL, String charset,Context c,int length)
throws IOException{
this.charset = charset;
context=c;
android_id=Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
// creates a unique boundary based on time stamp
//boundary = "===" + System.currentTimeMillis() + "===";
boundary = "----123456789----";

URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
//httpConn.setChunkedStreamingMode(buffer_size);
//httpConn.setFixedLengthStreamingMode();//4096
httpConn.setDoOutput(true); // indicates POST method
//httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
//httpConn.setRequestProperty("host","genuinesell.com");
//httpConn.setRequestProperty("ACCEPT_LANGUAGE","en-US,en;q=0.5");
httpConn.setRequestProperty("connection", "close");
//httpConn.setRequestProperty("ACCEPT","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//httpConn.setRequestProperty("ENCTYPE", "multipart/form-data");
httpConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
//httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; U; ABrowse 0.6;SyllableAppleWebKit/420+(KHTML, like Gecko)");
httpConn.setRequestProperty("id",android_id);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),true);
}

/**
 * Adds a form field to the request
 * @ param name field name
 * @ param value field value
 */
public void addProgress(Progress p){progress=p;}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}

/**
 * Adds a upload file section to the request
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + fieldName+ "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();

FileInputStream inputStream = new FileInputStream(uploadFile);
long total=inputStream.available();
byte[] buffer = new byte[buffer_size];
int bytesRead = -1;
long sent=0;
second_prog++;
//int buffersize= (int)Math.min(total,buffer_size);
while ((bytesRead = inputStream.read(buffer)) != -1){
//while ((bytesRead = inputStream.read(buffer,0,buffer_size)) != -1){
try{outputStream.write(buffer,0,bytesRead);
//outputStream.flush();

}catch(OutOfMemoryError e){Log.d("eeeeeeeeeeeee",e.toString());
}
sent+=bytesRead;
progress.onUpload(sent,total,second_prog);
}

outputStream.flush();
inputStream.close();

writer.append(LINE_FEED);
writer.flush();

}

/**
 * Adds a header field to the request.
 * @param name - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}

/**
 * Completes the request and receives response from the server.
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();

writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();

// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}

return response;
}















public int uploadFile(String sourceFileUri,String url_link) {
int serverResponseCode=00;

String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);

if (!sourceFile.isFile()) {

//dialog.dismiss();
Log.e("uploadFile","Source File not exist :");


return 0;

}
else
{
try {

// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url_link);

// Open a HTTP  connection to  the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
               + fileName + "\"" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of  maximum size
bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...
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);

// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){
/*
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
             +" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(context,"File Upload Complete.",Toast.LENGTH_SHORT).show();
}
});*/
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {

//dialog.dismiss();
ex.printStackTrace();
/*
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(context, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});*/
Log.d("sssssss","malformaer url");

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

//dialog.dismiss();
e.printStackTrace();

Log.d("sssssss","exeption found");
Log.e("eeeeeeeeeeeeee", "Exception : "  + e.getMessage(), e);
}
//dialog.dismiss();
return serverResponseCode;

} // End else block
}





public interface Progress {
void onUpload(long uploaded, long total,int second);

}
}

,这是AsyncTask

public void file(final String url,final ArrayList<String> imgPaths,final myHttpOnFinished o,final myHttpBeforSend bs, final FileUploader.Progress prg) {
new AsyncTask<String, Void, String>() {

@Override
protected String doInBackground(String... params){
String charset = "UTF-8";
File sourceFile[] = new File[imgPaths.size()];
for (int i=0;i<imgPaths.size();i++){
sourceFile[i] = new File(imgPaths.get(i));
// Toast.makeText(getApplicationContext(),imgPaths.get(i),Toast.LENGTH_SHORT).show();
}
int length=102400;
StringBuffer data=new StringBuffer();
try {
FileUploader multipart = new FileUploader(url, charset,context,length
);
 multipart.addProgress(prg);
bs.run(multipart);

for (int i=0;i<imgPaths.size();i++){
multipart.addFilePart("files[]", sourceFile[i]);
}

List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");

for(String line : response) {
System.out.println(line);
data.append(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
return data.toString();
}
@Override
public void onPostExecute(final String re) {
o.run(re);
}
}.execute();

}

0 个答案:

没有答案