當前位置:首頁 » 安卓系統 » androidhttp上傳

androidhttp上傳

發布時間: 2022-12-09 17:22:08

A. android的自帶的httpClient 怎麼上傳文件

這里只貼出代碼,可根據實際情況自行修改。

[java]
package com.lxb.uploadwithprogress.http;

import java.io.File;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;

public class HttpMultipartPost extends AsyncTask
{

private Context context;
private String filePath;
private ProgressDialog pd;
private long totalSize;

public HttpMultipartPost(Context context, String filePath) {
this.context = context;
this.filePath = filePath;
}

@Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage(Uploading Picture...);
pd.setCancelable(false);
pd.show();
}

@Override
protected String doInBackground(String... params) {
String serverResponse = null;

HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(上傳URL, 如:http://www.xx.com/upload.php);

try {
CustomMultipartEntity multipartContent = new CustomMultipartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});

// We use FileBody to transfer an image
multipartContent.addPart(data, new FileBody(new File(
filePath)));
totalSize = multipartContent.getContentLength();

// Send it
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
serverResponse = EntityUtils.toString(response.getEntity());

} catch (Exception e) {
e.printStackTrace();
}

return serverResponse;
}

@Override
protected void onProgressUpdate(Integer... progress) {
pd.setProgress((int) (progress[0]));
}

@Override
protected void onPostExecute(String result) {
System.out.println(result: + result);
pd.dismiss();
}

@Override
protected void onCancelled() {
System.out.println(cancle);
}

}
[java]
package com.lxb.uploadwithprogress.http;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

public class CustomMultipartEntity extends MultipartEntity {

private final ProgressListener listener;

public CustomMultipartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}

public CustomMultipartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}

public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}

@Override
public void writeTo(OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}

public static interface ProgressListener {
void transferred(long num);
}

public static class CountingOutputStream extends FilterOutputStream {

private final ProgressListener listener;
private long transferred;

public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}

public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}

public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}

}
上面為兩個主要的類,下面放一個調用的Activity

B. Android Q 上基於 OkHttp 上傳(大)文件的實現

如圖,RequestBody 有好幾個 create 方法,可以滿足不同場景下的內容上傳,比如字元串、位元組數組和文件。

顯然,字元串和位元組數組是不能上傳大文件的,均可能 OOM。

那麼,就只能使用 RequestBody create(MediaType contentType, File file) 方法了。正常情況下也是沒什麼問題的,但是在 Android Q 上,由於存儲許可權的變更,將導致無法直接訪問從內容庫所選擇的文件。

得到如下日誌:

可見,即使通過 uri 得到了文件的真實路徑,也是無法直接訪問的。

通過上面的實驗可以看到,我們是無法直接通過 File 相關的 API 訪問原始文件的,但是我們卻可以通過 ContentResolver 得到原始文件的流。

類似地,可以基於流或者 FileDescriptor 對圖片解碼成 Bitmap,參考:

C. android 怎麼多圖上傳 okhttp

android上傳圖片是先將圖片文件轉換成流文件:可用以下代碼轉換流文件,imgPath為圖片的完整地址
//圖片轉化成base64字元串
public static String imgToBase64(String imgPath) {
InputStream in = null;
byte[] data = null;
//讀取圖片位元組數組
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e){
e.printStackTrace();
}
//對位元組數組Base64編碼
sun.misc.BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64編碼過的位元組數組字元串
}
然後圖片文件就成為一串字元串啦,傳遞方法和普通字元串一樣,多圖使用分號隔開即可,後台收到後直接將流文件轉換成圖片保存即可。

D. Android中如何實現帶進度的文件上傳Http可以實現嗎

可使用android自帶的httpclient框架實現,附件中已經現成的示例代碼,帶上傳進度。


1. GET 方式傳遞參數

//先將參數放入List,再對參數進行URL編碼

List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();

params.add(new BasicNameValuePair("param1", "數據")); //增加參數1

params.add(new BasicNameValuePair("param2", "value2"));//增加參數2

String param = URLEncodedUtils.format(params, "UTF-8");//對參數編碼

String baseUrl = "伺服器介面完整URL";

HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數拼接

HttpClient httpClient = new DefaultHttpClient();

try {

HttpResponse response = httpClient.execute(getMethod); //發起GET請求

Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼

Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取伺服器響應內容

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}


2.POST方式 方式傳遞參數

//和GET方式一樣,先將參數放入List

params = new LinkedList<BasicNameValuePair>();

params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數1

params.add(new BasicNameValuePair("param2", "第二個參數"));//增加參數2

try {

HttpPost postMethod = new HttpPost(baseUrl);//創建一個post請求

postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中

HttpResponse response = httpClient.execute(postMethod); //執行POST方法

Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼

Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}


E. Android中使用HttpPost實現數據與文件同時上傳的功能

第一步:編寫一個Servlet,把接收到的HTTP信息保存在一個文件中,代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {
//獲取輸入流,是HTTP協議中的實體內容

ServletInputStream sis=request.getInputStream();
//緩沖區

byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream("d://file.log");

int len=sis.read(buffer, 0, 1024);
//把流里的信息循環讀入到file.log文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}
第二步:實現如下圖1的的表單頁面,生成一個注冊表單,提交到Servlet中

詳細的代碼如下:

<form action="servlet/ReceiveFile" method="post" enctype="multipart/form-data">
第一個參數<input type="text" name="name1"/> <br/>
第二個參數<input type="text" name="name2"/> <br/>
第一個上傳的文件<input type="file" name="file1"/> <br/>
第二個上傳的文件<input type="file" name="file2"/> <br/>
<input type="submit" value="提交">
</form>
注意了,由於要上傳附件,所以一定要設置enctype為multipart/form-data,才可以實現附件的上傳。
第三步:填寫完信息後按「提交」按鈕後,在D盤下查找file.log文件用記事本打開,數據如下:
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name1"
hello
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name2"
world
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="file1"; filename="C:/2.GIF"
Content-Type: image/gif
GIF89a

F. 如何在android實現HTTP多任務上傳文件

IntentService

G. android http協議可以上傳對象嗎

網上介紹Android上http通信的文章很多,不過大部分只給出了實現代碼的片段,一些注意事項和如何設計一個合理的類用來處理所有的http請求以及返回結果,一般都不會提及。因此,自己對此做了些總結,給出了我的一個解決方案。 首先,需要明確一下http通信流程,Android目前提供兩種http通信方式,HttpURLConnection和HttpClient,HttpURLConnection多用於發送或接收流式數據,因此比較適合上傳/下載文件,HttpClient相對來講更大更全能,但是速度相對也要慢一點。在此只介紹HttpClient的通信流程: 1work; import java.ConnectivityManager; import android.os.Handler; import android.util.Log; /** * * 用於封裝&簡化http通信 * */ public class PostRequest implements Runnable { private static final int NO_SERVER_ERROR=1000; //伺服器地址 public static final String URL = "fill your own url"; //一些請求類型 public final static String ADD = "/add"; public final static String UPDATE = "/update"; public final static String PING = "/ping"; //一些參數 private static int connectionTimeout = 60000; private static int socketTimeout = 60000; //類靜態變數 private static HttpClient httpClient=new DefaultHttpClient(); private static ExecutorService executorService=Executors.newCachedThreadPool(); private static Handler handler = new Handler(); //變數 private String strResult; private HttpPost httpPost; private HttpResponse httpResponse; private OnReceiveDataListener onReceiveDataListener; private int statusCode; /** * 構造函數,初始化一些可以重復使用的變數 */ public PostRequest() { strResult = null; httpResponse = null; httpPost = new HttpPost(); } /** * 注冊接收數據監聽器 * @param listener */ public void setOnReceiveDataListener(OnReceiveDataListener listener) { onReceiveDataListener = listener; } /** * 根據不同的請求類型來初始化httppost * * @param requestType * 請求類型 * @param nameValuePairs * 需要傳遞的參數 */ public void iniRequest(String requestType, JSONObject jsonObject) { httpPost.addHeader("Content-Type", "text/json"); httpPost.addHeader("charset", "UTF-8"); httpPost.addHeader("Cache-Control", "no-cache"); HttpParams httpParameters = httpPost.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); httpPost.setParams(httpParameters); try { httpPost.setURI(new URI(URL + requestType)); httpPost.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8)); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 新開一個線程發送http請求 */ public void execute() { executorService.execute(this); } /** * 檢測網路狀況 * * @return true is available else false */ public static boolean checkNetState(Activity activity) { ConnectivityManager connManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); if (connManager.getActiveNetworkInfo() != null) { return connManager.getActiveNetworkInfo().isAvailable(); } return false; } /** * 發送http請求的具體執行代碼 */ @Override public void run() { httpResponse = null; try { httpResponse = httpClient.execute(httpPost); strResult = EntityUtils.toString(httpResponse.getEntity()); } catch (ClientProtocolException e1) { strResult = null; e1.printStackTrace(); } catch (IOException e1) { strResult = null; e1.printStackTrace(); } finally { if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { statusCode=NO_SERVER_ERROR; } if(onReceiveDataListener!=null) { //將注冊的監聽器的onReceiveData方法加入到消息隊列中去執行 handler.post(new Runnable() { @Override public void run() { onReceiveDataListener.onReceiveData(strResult, statusCode); } }); } } } /** * 用於接收並處理http請求結果的監聽器 * */ public interface OnReceiveDataListener { /** * the callback function for receiving the result data * from post request, and further processing will be done here * @param strResult the result in string style. * @param StatusCode the status of the post */ public abstract void onReceiveData(String strResult,int StatusCode); } } 代碼使用了觀察者模式,任何需要接收http請求結果的類,都要實現OnReceiveDataListener介面的抽象方法,同時PostRequest實例調用setOnReceiveDataListener方法,注冊該監聽器。完整調用步驟如下: 1.創建PostRequest對象,實現onReceiveData介面,編寫自己的onReceiveData方法 2.注冊監聽器 3.調用PostRequest的iniRequest方法,初始化本次request 4.調用PostRequest的execute方法 可能的改進: 1.如果需要多個觀察者,可以把只能注冊單個監聽器改為可以注冊多個監聽器,維護一個監聽器List。 2.如果需求比較簡單,並希望調用流程更簡潔,iniRequest和execute可以合並

H. android-async-http批量上傳

我這有個httpclient寫的工具類
批量上傳的話,只需要傳遞一個FIle對象還可以帶上傳進度條

服務端的話就簡單了
如果是struts的話,只要定義一個fileUpload的攔截器,定義一個List<File> 對象就會自動注入了
如果是servlet的話,那就要用FileUpload + io 兩個架包,自己寫代碼去讀取文件了

我這有個客戶端,android寫的

I. android http協議上傳數據內存溢出怎麼處理

對於虛擬內存主要設置兩點,即內存大小和存放位置,內存大小就是設置虛擬內存最小為多少和最大為多少;而存放位置則是設置虛擬內存應使用哪個分區中的硬碟空間。對於內存大小的設置,如何得到最小值和最大值呢?你可以通過下面的方法獲得:選擇「開始→程序→附件→系統工具→系統監視器」(如果系統工具中沒有,可以通過「添加/刪除程序」中的Windows安裝程序進行安裝)打開系統監視器,然後選擇「編輯→添加項目」,在「類型」項中選擇「內存管理程序」,在右側的列表選擇「交換文件大小」。這樣隨著你的操作,會顯示出交換文件值的波動情況,你可以把經常要使用到的程序打開,然後對它們進行使用,這時查看一下系統監視器中的表現值,由於用戶每次使用電腦時的情況都不盡相同,因此,最好能夠通過較長時間對交換文件進行監視來找出最符合您的交換文件的數值,這樣才能保證系統性能穩定以及保持在最佳的狀態。一般來說,交換文件太大不會影響效率,但會佔用額外的磁碟空間。交換文件太小有時會引起可以運行的程序數量變少。 找出最合適的范圍值後,在設置虛擬內存時,用滑鼠右鍵點擊「我的電腦」,選擇「屬性」,彈出系統屬性窗口,選擇「性能」標簽,點擊下面「虛擬內存」按鈕,彈出虛擬內存設置窗口,點擊「用戶自己指定虛擬內存設置」單選按鈕,「硬碟」選較大剩餘空間的分區,然後在「最小值」和「最大值」文本框中輸入合適的范圍值。如果您感覺使用系統監視器來獲得最大和最小值有些麻煩的話,這里完全可以選擇「讓Windows管理虛擬內存設置」。 調整分頁位置 Windows9x的虛擬內存分頁位置,其實就是保存在C盤根目錄下的一個虛擬內存文件(也稱為交換文件)Win386.swp,它的存放位置可以是任何一個分區,如果系統盤C容量有限,我們可以把Win386.swp調到別的分區中,方法是在記事本中打開System.ini(C:Windows下)文件,在[386Enh]小節中,將「PagingDrive=C:WindowsWin386.swp」,改為其他分區的路徑,如將交換文件放在D:中,則改為「PagingDrive=D:Win386.swp」,如沒有上述語句可以直接鍵入即可。 而對於使用Windows2000和WindowsXP的,可以選擇「控制面板→系統→高級→性能」中的「設置→高級→更改」,打開虛擬內存設置窗口,在驅動器[卷標]中默認選擇的是系統所在的分區,如果想更改到其他分區中,首先要把原先的分區設置為無分頁文件,然後再選擇其他分區。 或者,WinXP一般要求物理內存在256M以上。如果你喜歡玩大型3D游戲,而內存(包括顯存)又不夠大,系統會經常提示說虛擬內存不夠,系統會自動調整(虛擬內存設置為系統管理)。 如果你的硬碟空間夠大,你也可以自己設置虛擬內存,具體步驟如下:右鍵單擊「我的電腦」→屬性→高級→性能設置→高級→虛擬內存更改→選擇虛擬內存(頁面文件)存放的分區→自定義大小→確定最大值和最小值→設置。一般來說,虛擬內存為物理內存的1.5倍,稍大一點也可以,如果你不想虛擬內存頻繁改動,可以將最大值和最小值設置為一樣。{另一種說法:調整時我們需要注意,不要將最大、最小頁面文件設為等值。因為通常內存不會真正「塞滿」,它會在內存儲量到達一定程度時,自動將一部分暫時不用的數據放到硬碟中。最小頁面文件越大,所佔比例就低,執行的速度也就越慢。最大頁面文件是極限值,有時打開很多程序,內存和最小頁面文件都已「塞滿」,就會自動溢出到最大頁面文件。所以將兩者設為等值是不合理的。一般情況下,最小頁面文件設得小些,這樣能在內存中盡可能存儲更多數據,效率就越高。最大頁面文件設得大些,以免出現「滿員」的情況。 PS:①1.5倍虛擬內存設置,是網上技術文檔通用說明的,個人認為可以根據常用軟體的實際情況設定。推薦有經驗的用戶使用。 ②現在有很多工具軟體(例如WINDOWS優化大師、超級兔子),可以很好的更改這些設置,工具軟體也會根據你的電腦的實際情況進行相應的推薦設置。

J. android使用httpURLconnection怎麼同時上傳文件和參數到伺服器

// 首先組拼文本類型的參數
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
outStream.write(sb.toString().getBytes());

熱點內容
預算管理如何實現資源配置 發布:2025-03-16 01:33:02 瀏覽:615
阿里雲伺服器上傳圖片指令 發布:2025-03-16 01:27:25 瀏覽:27
狼戰2ftp 發布:2025-03-16 01:27:18 瀏覽:676
android濾波 發布:2025-03-16 01:25:02 瀏覽:623
海南省源碼 發布:2025-03-16 01:20:36 瀏覽:378
java程序員修煉之道 發布:2025-03-16 01:15:46 瀏覽:829
離子存儲 發布:2025-03-16 01:02:46 瀏覽:258
免費上傳雲盤 發布:2025-03-16 01:01:59 瀏覽:706
acm配置是什麼 發布:2025-03-16 00:56:56 瀏覽:647
安卓系統怎麼通話 發布:2025-03-16 00:25:13 瀏覽:320