Android上傳檔案到服務端可以使用HttpConnection 上傳檔案,也可以使用Android封裝好的HttpClient類。當僅僅上傳檔案可以直接使用httpconnection 上傳比較方便快捷。
1、使用HttpConection上傳檔案。將檔案轉換成表單資料流。主要的思路就自己構造個http協議內容,服務端解析報文獲得表單資料。程式碼片段:
[java]
HttpURLConnection con;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(C_TimeOut);
/* 允許Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 設定傳送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
/* 設定DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
FileInputStream fStream = new FileInputStream(file);
/* 設定每次寫入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 從檔案讀取資料至緩衝區 */
while((length = fStream.read(buffer)) != -1)
{
/* 將資料寫入DataOutputStream中 */
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
ds.close();
可以參考
①《在 Android 上通過類比 HTTP multipart/form-data 請求協議資訊實現圖片上傳》 ②《關於android Http訪問,上傳,用了三個方法 》
2、使用Android HttpClient類上傳參數。下面我在網上搜到得代碼,忘記出處了
[java]
private static boolean sendPOSTRequestHttpClient(String path,
Map<String, String> params) throws Exception {
// 封裝請求參數
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把請求參數變成請求體部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost對象設定發送的URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(uee);
// 建立一個瀏覽器對象,以把POST對象向伺服器發送,並返迴響應訊息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
Log.i("http", "httpclient");
return true;
}
return false;
}
3、使用httpClient上傳文字資訊和檔案資訊。使用httpClient上傳檔案非常的方便。不過需要匯入apache-mime4j-0.6.jar 和httpmime-4.0.jar兩個.jar包。
[java]
// 封裝請求參數
MultipartEntity mpEntity = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
StringBody par = new StringBody(entry.getValue());
mpEntity.addPart(entry.getKey(), par);
}
}
// 圖片
if (!imagepath.equals("")) {
FileBody file = new FileBody(new File(imagepath));
mpEntity.addPart("photo", file);
}
// 使用HttpPost對象設定發送的URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(mpEntity);
// 建立一個瀏覽器對象,以把POST對象向伺服器發送,並返迴響應訊息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
FileBody類可以把檔案封裝到表單中,實現附件的上傳。
作者:安客成