httpclient上傳
❶ 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/
❷ 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();
}
❸ 如何接收httpclient 文件上傳
一般的情況下我們都是使用Chrome或者其他瀏覽器來訪問一個WEB伺服器,用來瀏覽頁面查看信息或者提交一些數據、文件上傳下載等等。所訪問的這些頁面有的僅僅是一些普通的頁面,有的需要用戶登錄後方可使用,或者需要認證以及是一些通過加密方式傳輸,例如H
❹ HTTPclient使用MultipartEntity怎麼上傳文件
你先搞清楚 HTTPclient 是做什麼用的
HTTPclient 的作用是在 jsp 中模擬一個瀏覽器,即 HTTP 協議的客戶端(client)
你的後台代碼是將你本地伺服器上的文件像瀏覽器那樣上傳到目標伺服器
於是 new File("C:\\1.txt") 的問題就可以解決了吧?C:\\1.txt 是你本地伺服器中的文件,當然文件名是你自己定的
至於 multipart/form-data 聲明,那是由 HttpPost 的參數 MultipartEntity 自動加上的
❺ android的自帶的httpClient 怎麼上傳文件
分享一段前輩的demo,希望對你有幫助,
/**
* 上傳文件
* @throws ParseException
* @throws IOException
*/
public static void postFile() throws ParseException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 要上傳的文件的路徑
String filePath = new String("F:/pic/001.jpg");
// 把一個普通參數和文件上傳給下模李面這個地址 是一個servlet
HttpPost httpPost = new HttpPost(
"http://localhost:8080/xxx/xxx.action");
// 把文件轉換成流對象FileBody
File file = new File(filePath);
FileBody bin = new FileBody(file);
StringBody uploadFileName = new StringBody(
"把我修改成文件名稱", ContentType.create(
"正並text/plain", Consts.UTF_8));
//以瀏覽器兼容模式運行,防止文件名亂碼。
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("uploadFile", bin) //uploadFile對應服務端類的同名屬性<File類型>
.addPart("uploadFileName", uploadFileName)//uploadFileName對應服務端類的同名屬性<String類型>
.setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);
System.out.println("發起請求的頁面地址 " + httpPost.getRequestLine());
// 發起請求 並返回請求的響應
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println("----------------------------------------");
// 列印響應狀態
System.out.println(response.getStatusLine());
// 獲取響應對舉碼跡象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 列印響應長度
System.out.println("Response content length: "
+ resEntity.getContentLength());
// 列印響應內容
System.out.println(EntityUtils.toString(resEntity,
Charset.forName("UTF-8")));
}
// 銷毀
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
/**
* 下載文件
* @param url http://www.xxx.com/img/333.jpg
* @param destFileName xxx.jpg/xxx.png/xxx.txt
* @throws ClientProtocolException
* @throws IOException
*/
public static void getFile(String url, String destFileName)
throws ClientProtocolException, IOException {
// 生成一個httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
File file = new File(destFileName);
try {
FileOutputStream fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
// 注意這里如果用OutputStream.write(buff)的話,圖片會失真,大家可以試試
}
fout.flush();
fout.close();
} finally {
// 關閉低層流。
in.close();
}
httpclient.close();
}
❻ HTTPclient使用MultipartEntity怎麼上傳文件
上傳文檔方法:
進入網路文庫後,點「上傳我的文檔」,會出現一個對話框,選擇你想要上傳的文檔,再點擊「開始上傳」。
注意文檔有格式要求,上傳後等待審核,通過後即可與網友共享了。
上傳附件方法:
步驟一:展開回答框,找到「上傳」按鈕
步驟二:點擊「上傳」按鈕,從電腦中選擇要上傳的文件(目前只支持上傳1個文件哦~如果有多個文件,可以進行打包上傳~~)
步驟三:選中文件打開,顯示文件上傳進度。
步驟四:文件上傳成功,進度條顯示100%,可以對文件進行重命名操作~~
步驟五:回答編輯成功後,進入問題頁顯示,可供網友下載~~
❼ android的自帶的httpClient 怎麼上傳文件
Android上傳文件到服務端可以使用HttpConnection 上傳文件,也可以使用Android封裝好的HttpClient類。當僅僅上傳文件可以直接使用httpconnection 上傳比較方便快捷。
1、使用HttpConection上傳文件。將文件轉換成表單數據流。主要的思路就自己構造個http協議內容,服務端解析報文獲得表單數據。代碼片段:
[java] view plain
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 請求協議信息實現圖片上傳》 (http://bertlee.iteye.com/blog/1134576)。
②《關於android Http訪問,上傳,用了三個方法 》
2、使用Android HttpClient類上傳參數。下面我在網上搜到得代碼,忘記出處了
[java] view plain
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] view plain
// 封裝請求參數
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類可以把文件封裝到表單中,實現附件的上傳。
關於httpClient上傳文件可以參考鏈接: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=76721&page=1
需要用的的ja下載地址r:http://download.csdn.net/detail/china1988s/3791514
參考:
①《在 Android 上通過模擬 HTTP multipart/form-data 請求協議信息實現圖片上傳》 (http://bertlee.iteye.com/blog/1134576)。
②《關於android Http訪問,上傳,用了三個方法 》
❽ 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" />
附件中包含了一個拍照上傳的源代碼