當前位置:首頁 » 文件管理 » httpclient43文件上傳

httpclient43文件上傳

發布時間: 2022-08-21 17:04:10

A. 求助,文件的上傳/下載,都是用什麼技術實現的

在實現一個Android的WEB服務客戶端,比如微博,論壇客戶端時,經常會使用到圖片的上傳和下載。在這里介紹如何利用HttpClient實現圖片的上傳和下載功能。

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

在Android開發中,Android SDK附帶了Apache的HttpClient,它是一個完善的客戶端。它提供了對HTTP協議的全面支持,可以使用HttpClient的對象來執行HTTP GET和HTTP POST調用。

HTTP工作原理:

1.客戶端(一般是指瀏覽器,這里是指自己寫的程序)與伺服器建立連接

2.建立連接後,客戶端向伺服器發送請求

3.伺服器接收到請求後,向客戶端發送響應信息

4.客戶端與伺服器斷開連接


HttpClient的一般使用步驟:

1.使用DefaultHttpClient類實例化HttpClient對象

2.創建HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。

3.調用execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。

4.通過HttpResponse介面的getEntity方法返回響應信息,並進行相應的處理。

最後記得要在AndroidManifest.xml文件添加網路許可權

<uses-permission android:name="android.permission.INTERNET" />


附件中包含了一個拍照上傳的源代碼


C. commons-httpclient如何實現文件上傳

在struts2中結合HttpClient進行文件上傳
最近遇到了用httpclient進行上傳文件的問題,下面我就和大家簡單的說一下:
package com.imps.action;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class TabinfoAction extends BaseAction
{
private File[] myFile;
private String[] myFileFileName;// 文件名
private Integer[] myFileFileSize;// 文件大小
private String[] myFileContentType;// 文件類型

public String uploadPost()
{
String posturl ="http://127.0.0.1:8080/settabimage.aspx";
System.out.println(posturl);
String status=null;
for(int i=0;i<myFile.length;i++)
{
FileInputStream file=new FileInputStream(myFile[i]);
InputStream in = new BufferedInputStream(file);
PostMethod post=new PostMethod(posturl);
post.setRequestBody(in);
HttpClient client = new HttpClient();
client.executeMethod(post);
String response=new String(post.getResponseBodyAsString().getBytes("ISO-8859-1"),"UTF-8");
post.releaseConnection();
in.close();
file.close();
}
}

public File[] getMyFile() {
return myFile;
}

public void setMyFile(File[] myFile) {
this.myFile = myFile;
}

public String[] getMyFileFileName() {
return myFileFileName;
}

public void setMyFileFileName(String[] myFileFileName) {
this.myFileFileName = myFileFileName;
}

public Integer[] getMyFileFileSize() {
return myFileFileSize;
}

public void setMyFileFileSize(Integer[] myFileFileSize) {
this.myFileFileSize = myFileFileSize;
}

public String[] getMyFileContentType() {
return myFileContentType;
}

public void setMyFileContentType(String[] myFileContentType) {
this.myFileContentType = myFileContentType;
}
千萬記住不要記忘記關閉流和釋放http連接

D. 如何接收httpclient 文件上傳

一般的情況下我們都是使用Chrome或者其他瀏覽器來訪問一個WEB伺服器,用來瀏覽頁面查看信息或者提交一些數據、文件上傳下載等等。所訪問的這些頁面有的僅僅是一些普通的頁面,有的需要用戶登錄後方可使用,或者需要認證以及是一些通過加密方式傳輸,例如H

E. httpclient 怎麼實現多文件上傳 c/s java

雖然在JDK的java.net包中已經提供了訪問HTTP協議的基本功能,但是對於大部分應用程序來說,JDK庫本身提供的功能還不夠豐富和靈活。HttpClient是ApacheJakartaCommon下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。以下是簡單的post例子:Stringurl="bbslogin2.php";PostMethodpostMethod=newPostMethod(url);//填入各個表單域的值NameValuePair[]data={newNameValuePair("id","youUserName"),newNameValuePair("passwd","yourPwd")};//將表單的值放入postMethod中postMethod.setRequestBody(data);//執行postMethodintstatusCode=httpClient.executeMethod(postMethod);//HttpClient對於要求接受後繼服務的請求,象POST和PUT等不能自動處理轉發//301或者302if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY){//從頭中取出轉向的地址HeaderlocationHeader=postMethod.getResponseHeader("location");Stringlocation=null;if(locationHeader!=null){location=locationHeader.getValue();System.out.println("Thepagewasredirectedto:"+location);}else{System.err.println("Locationfieldvalueisnull.");}return;}詳情見:/developerworks/cn/opensource/os-httpclient/

F. HTTPclient使用MultipartEntity怎麼上傳文件

後台的代碼都是這樣寫的

MultipartEntity entity = new MultipartEntity();
entity.addPart("param1", new StringBody("中國", Charset.forName("UTF-8")));
entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));
entity.addPart("param3", new FileBody(new File("C:\\1.txt")));

HttpPost request = new HttpPost(「http://localhost/index.html」);
request.setEntity(entity);
在這里HTTPclient 的作用是在 jsp 中模擬一個瀏覽器,即 HTTP 協議的客戶端(client)
你的後台代碼是將你本地伺服器上的文件像瀏覽器那樣上傳到目標伺服器
C:\\1.txt 是你本地伺服器中的文件,當然文件名是你自己定的

至於 multipart/form-data 聲明,那是由 HttpPost 的參數 MultipartEntity 自動加上的

G. 如何在struts2中結合HttpClient進行文件上傳

攔截器增加file攔截器

頁面寫個<input type="file" name="upload"/>

後台action里定義一個upload成員變數,並鞋號getter和setter方法

文件直接就映射到action的upload屬性里了,主要是要配置上file攔截器,basicStack是沒有file攔截器的,defaultStack里包括了file攔截器

H. 如何使用HttpClient

一般的情況下我們都是使用IE或者Navigator瀏覽器來訪問一個WEB伺服器,用來瀏覽頁面查看信息或者提交一些數據等等。所訪問的這些頁面有的僅僅是一些普通的頁面,有的需要用戶登錄後方可使用,或者需要認證以及是一些通過加密方式傳輸,例如HTTPS。
目前我們使用的瀏覽器處理這些情況都不會構成問題。不過你可能在某些時候需要通過程序來訪問這樣的一些頁面,比如從別人的網頁中「偷」一些數據;利用某些站點提供的頁面來完成某種功能,例如說我們想知道某個手機號碼的歸屬地而我們自己又沒有這樣的數據,因此只好藉助其他公司已有的網站來完成這個功能,這個時候我們需要向網頁提交手機號碼並從返回的頁面中解析出我們想要的數據來。如果對方僅僅是一個很簡單的頁面,那我們的程序會很簡單,本文也就沒有必要大張旗鼓的在這里浪費口舌。
但是考慮到一些服務授權的問題,很多公司提供的頁面往往並不是可以通過一個簡單的URL就可以訪問的,而必須經過注冊然後登錄後方可使用提供服務的頁面,這個時候就涉及到COOKIE問題的處理。我們知道目前流行的動態網頁技術例如ASP、JSP無不是通過COOKIE來處理會話信息的。為了使我們的程序能使用別人所提供的服務頁面,就要求程序首先登錄後再訪問服務頁面,這過程就需要自行處理cookie,想想當你用java.net.HttpURLConnection來完成這些功能時是多麼恐怖的事情啊!況且這僅僅是我們所說的頑固的WEB伺服器中的一個很常見的「頑固」!
再有如通過HTTP來上傳文件呢?不需要頭疼,這些問題有了「它」就很容易解決了!

I. 如何獲得一個文件的上傳與Apache HttpClient的4進度條

1. 我介紹一個派生FileEntity只是計數寫入的位元組。OutputStreamProgress做了實際的計數(一種裝飾器的實際OutputStream)。 這樣做的好處(與裝修一般)是,我不需要從文件流復制的實際就像實際的復制到輸出流。我也可以改變一個不同的(新)之類的NFileEntity。 享受... FileEntity.javapublic class FileEntity extends org.apache.http.entity.FileEntity {

private OutputStreamProgress outstream;

public FileEntity(File file, String contentType) {
super(file, contentType);
}

@Override
public void writeTo(OutputStream outstream) throws IOException {
this.outstream = new OutputStreamProgress(outstream);
super.writeTo(this.outstream);
}

/**
* Progress: 0-100
*/
public int getProgress() {
if (outstream == null) {
return 0;
}
long contentLength = getContentLength();
if (contentLength <= 0) { // Prevent division by zero and negative values
return 0;
}
long writtenLength = outstream.getWrittenLength();
return (int) (100*writtenLength/contentLength);
}
}

OutputStreamProgress.javapublic class OutputStreamProgress extends OutputStream {

private final OutputStream outstream;
private volatile long bytesWritten=0;

public OutputStreamProgress(OutputStream outstream) {
this.outstream = outstream;
}

@Override
public void write(int b) throws IOException {
outstream.write(b);
bytesWritten++;
}

@Override
public void write(byte[] b) throws IOException {
outstream.write(b);
bytesWritten += b.length;
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
outstream.write(b, off, len);
bytesWritten += len;
}

@Override
public void flush() throws IOException {
outstream.flush();
}

@Override
public void close() throws IOException {
outstream.close();
}

public long getWrittenLength() {
return bytesWritten;
}
}

2. 這個答案通過添加一個簡單的監聽器OutputStreamProgress.java類,而不是由公眾getProgress()方法(我真的不知道你是如何想調用getProgress()方法,因為該線程會執行內部延伸kilaka的回答的HttpClient的代碼,整個你可能需要調用getProgress()!)。 請注意,您需要延長您希望每個實體類型的實體類,當你寫你的HttpClient代碼,你需要創建一個新的類型的實體。 我寫了一個非常基本的寫聽者的WriteListener介面。在這里,您將添加你的邏輯做從OutputStreamProgress寫報告,如更新一個進度條:) 非常感謝kilaka裝飾理念在點票outstream潛行。 WriteLisener.javapublic interface WriteListener {
void registerWrite(long amountOfBytesWritten);
}

OutputStreamProgress.javaimport java.io.IOException;
import java.io.OutputStream;

public class OutputStreamProgress extends OutputStream {

private final OutputStream outstream;
private long bytesWritten=0;
private final WriteListener writeListener;
public OutputStreamProgress(OutputStream outstream, WriteListener writeListener) {
this.outstream = outstream;
this.writeListener = writeListener;
}

@Override
public void write(int b) throws IOException {
outstream.write(b);
bytesWritten++;
writeListener.registerWrite(bytesWritten);
}

@Override
public void write(byte[] b) throws IOException {
outstream.write(b);
bytesWritten += b.length;
writeListener.registerWrite(bytesWritten);
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
outstream.write(b, off, len);
bytesWritten += len;
writeListener.registerWrite(bytesWritten);
}

@Override
public void flush() throws IOException {
outstream.flush();
}

@Override
public void close() throws IOException {
outstream.close();
}
}

BasicWriteListenerpublic class BasicWriteListener implements WriteListener {

public BasicWriteListener() {
// TODO Auto-generated constructor stub
}

public void registerWrite(long amountOfBytesWritten) {
System.out.println(amountOfBytesWritten);
}

}

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 extends MultipartEntity {
private OutputStreamProgress outstream;
private WriteListener writeListener;

@Override
public void writeTo(OutputStream outstream) throws IOException {
this.outstream = new OutputStreamProgress(outstream, writeListener);
super.writeTo(this.outstream);
}

public (WriteListener writeListener)
{
super();
this.writeListener = writeListener;
}
public (HttpMultipartMode mode, WriteListener writeListener)
{
super(mode);
this.writeListener = writeListener;
}
public (HttpMultipartMode mode, String boundary, Charset charset, WriteListener writeListener)
{
super(mode, boundary, charset);
this.writeListener = writeListener;
}

// Left in for clarity to show where I took from kilaka's answer
// /**
// * Progress: 0-100
// */
// public int getProgress() {
// if (outstream == null) {
// return 0;
// }
// long contentLength = getContentLength();
// if (contentLength <= 0) { // Prevent division by zero and negative values
// return 0;
// }
// long writtenLength = outstream.getWrittenLength();
// return (int) (100*writtenLength/contentLength);
// }

}

3. 一個新的包組織結構。從公地-10(2.4)和它的類CountingOutputStream。 我改變了最初的代碼,以反映我的項目需要一個多形式輸入,(這個會費的徵收伺服器端)。 想想看,大文件的增量在我的測試中對應於4096個位元組。該counterChanged()被調用傳輸的數據的每4096位元組,什麼是可以接受的情況。 看起來像:public void post(String url, File sendFile) {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url + "/" + sendFile.getName());
MultipartEntity multiEntity = new MultipartEntity();
MyFileBody fileBody = new MyFileBody(sendFile);

fileBody.setListener(new IStreamListener(){

@Override
public void counterChanged(int delta) {
// do something
System.out.println(delta);
}});

multiEntity.addPart("file", fileBody);
StringBody stringBody = new StringBody(sendFile.getName());
multiEntity.addPart("fileName", stringBody);
post.setEntity(multiEntity);
HttpResponse response = client.execute(post);
}

類MyFileBodypublic class MyFileBody extends FileBody {

private IStreamListener listener;

public MyFileBody(File file) {
super(file);
}

@Override
public void writeTo(OutputStream out) throws IOException {
CountingOutputStream output = new CountingOutputStream(out) {
@Override
protected void beforeWrite(int n) {
if (listener != null && n != 0)
listener.counterChanged(n);
super.beforeWrite(n);
}
};
super.writeTo(output);

}

public void setListener(IStreamListener listener) {
this.listener = listener;
}

public IStreamListener getListener() {
return listener;
}

}

最後,監聽器介面的樣子:public interface IStreamListener {

void counterChanged(int delta);

}

J. httpclient如何一起上傳內容和圖片

以文件的形式傳參
/**
* 通過拼接的方式構造請求內容,實現參數傳輸以及文件傳輸
*
* @param actionUrl 訪問的伺服器URL
* @param params 普通參數
* @param files 文件參數
* @return
* @throws IOException
*/
public static void post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException
{

String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 緩存的最長時間
conn.setDoInput(true);// 允許輸入
conn.setDoOutput(true);// 允許輸出
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先組拼文本類型的參數
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());
InputStream in = null;
// 發送文件數據
if (files != null)
{
for (Map.Entry<String, File> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中傳參的鍵 filename是文件的名稱
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());

InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}

is.close();
outStream.write(LINEND.getBytes());
}

// 請求結束標志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到響應碼
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
}
// return in.toString();
}

以數據流的形式傳參
public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files)
throws Exception
{
StringBuilder sb2 = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(6 * 1000); // 緩存的最長時間
conn.setDoInput(true);// 允許輸入
conn.setDoOutput(true);// 允許輸出
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先組拼文本類型的參數
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());
InputStream in = null;
// 發送文件數據
if (files != null)
{
for (Map.Entry<String, byte[]> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());

// InputStream is = new FileInputStream(file.getValue());
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = is.read(buffer)) != -1)
// {
// outStream.write(buffer, 0, len);
// }
// is.close();
outStream.write(file.getValue());

outStream.write(LINEND.getBytes());
}

// 請求結束標志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到響應碼
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
System.out.println(sb2.toString());
}
outStream.close();
conn.disconnect();
// 解析伺服器返回來的數據
return ParseJson.getEditMadIconResult(sb2.toString());
}
else
{
return "Update icon Fail";
}
// return in.toString();
}

熱點內容
如何尋找資產配置機會 發布:2024-10-13 19:13:47 瀏覽:374
轎車安卓中控怎麼安裝手機卡 發布:2024-10-13 19:05:23 瀏覽:450
商城首頁android 發布:2024-10-13 17:53:20 瀏覽:496
甲骨文雲伺服器如何申請 發布:2024-10-13 16:49:39 瀏覽:135
c語言中參數傳遞 發布:2024-10-13 16:30:15 瀏覽:82
cos伺服器搭建 發布:2024-10-13 16:17:41 瀏覽:338
象棋軟體演算法 發布:2024-10-13 15:32:35 瀏覽:903
平板怎麼看真正配置 發布:2024-10-13 14:53:32 瀏覽:35
微信存儲空間的其他 發布:2024-10-13 14:52:14 瀏覽:672
怎麼繞過系統密碼登錄密碼登錄密碼登錄 發布:2024-10-13 14:47:41 瀏覽:510