HttpClient通過Post上傳文件的實(shí)例代碼
在之前一段的項(xiàng)目中,使用Java模仿Http Post方式發(fā)送參數(shù)以及文件,單純的傳遞參數(shù)或者文件可以使用URLConnection進(jìn)行相應(yīng)的處理。
但是項(xiàng)目中涉及到既要傳遞普通參數(shù),也要傳遞多個(gè)文件(不是單純的傳遞XML文件)。在網(wǎng)上尋找之后,發(fā)現(xiàn)是使用HttClient來進(jìn)行響應(yīng)的操作,起初嘗試多次依然不能傳遞參數(shù)和傳遞文件,后來發(fā)現(xiàn)時(shí)因?yàn)楫?dāng)使用HttpClient時(shí),不能使用request.getParameter()對普通參數(shù)進(jìn)行獲取,而要在服務(wù)器端使用Upload來進(jìn)行操作。
HttpClient4.2 jar下載 :http://download.csdn.net/detail/just_szl/4370574
客戶端代碼:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
*
* @author <a href="mailto:just_szl@hotmail.com"> Geray</a>
* @version 1.0,2012-6-12
*/
public class HttpPostArgumentTest2 {
//file1與file2在同一個(gè)文件夾下 filepath是該文件夾指定的路徑
public void SubmitPost(String url,String filename1,String filename2, String filepath){
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));
StringBody comment = new StringBody(filename1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file1", bin);//file1為請求后臺(tái)的File upload;屬性
reqEntity.addPart("file2", bin2);//file2為請求后臺(tái)的File upload;屬性
reqEntity.addPart("filename1", comment);//filename1為請求后臺(tái)的普通參數(shù);屬性
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
System.out.println("服務(wù)器正常響應(yīng).....");
HttpEntity resEntity = response.getEntity();
System.out.println(EntityUtils.toString(resEntity));//httpclient自帶的工具類讀取返回?cái)?shù)據(jù)
System.out.println(resEntity.getContent());
EntityUtils.consume(resEntity);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpPostArgumentTest2 httpPostArgumentTest2 = new HttpPostArgumentTest2();
httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveData.do",
"test.xml","test.zip","D://test");
}
}
服務(wù)端代碼:
public void receiveData(HttpServletRequest request, HttpServletResponse response) throws AppException{
PrintWriter out = null;
response.setContentType("text/html;charset=UTF-8");
Map map = new HashMap();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
File directory = null;
List<FileItem> items = new ArrayList();
try {
items = upload.parseRequest(request);
// 得到所有的文件
Iterator<FileItem> it = items.iterator();
while (it.hasNext()) {
FileItem fItem = (FileItem) it.next();
String fName = "";
Object fValue = null;
if (fItem.isFormField()) { // 普通文本框的值
fName = fItem.getFieldName();
// fValue = fItem.getString();
fValue = fItem.getString("UTF-8");
map.put(fName, fValue);
} else { // 獲取上傳文件的值
fName = fItem.getFieldName();
fValue = fItem.getInputStream();
map.put(fName, fValue);
String name = fItem.getName();
if(name != null && !("".equals(name))) {
name = name.substring(name.lastIndexOf(File.separator) + 1);
// String stamp = StringUtils.getFormattedCurrDateNumberString();
String timestamp_Str = TimeUtils.getCurrYearYYYY();
directory = new File("d://test");
directory.mkdirs();
String filePath = ("d://test")+ timestamp_Str+ File.separator + name;
map.put(fName + "FilePath", filePath);
InputStream is = fItem.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
fos.write(buffer, 0, buffer.length);
}
fos.flush();
fos.close();
map.put(fName + "FileName", name);
}
}
}
} catch (Exception e) {
System.out.println("讀取http請求屬性值出錯(cuò)!");
// e.printStackTrace();
logger.error("讀取http請求屬性值出錯(cuò)");
}
// 數(shù)據(jù)處理
try {
out = response.getWriter();
out.print("{success:true, msg:'接收成功'}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
以上所述是小編給大家介紹的HttpClient通過Post上傳文件的實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- HttpClient實(shí)現(xiàn)文件上傳功能
- C# HttpClient Post參數(shù)同時(shí)上傳文件的實(shí)現(xiàn)
- 基于HttpClient上傳文件中文名亂碼的解決
- C# 使用HttpClient上傳文件并附帶其他參數(shù)的步驟
- Android引用開源框架通過AsyncHttpClient實(shí)現(xiàn)文件上傳
- 使用HttpClient實(shí)現(xiàn)文件的上傳下載方法
- httpclient模擬post請求json封裝表單數(shù)據(jù)的實(shí)現(xiàn)方法
- Java利用HttpClient模擬POST表單操作應(yīng)用及注意事項(xiàng)
- HttpClient實(shí)現(xiàn)表單提交上傳文件
相關(guān)文章
android Animation監(jiān)聽器AnimationListener的使用方法)
AnimaitonListener的使用方法主要是在Animation上設(shè)置一個(gè)監(jiān)聽器,下面通過一個(gè)實(shí)例說明它的使用方法2013-11-11
使用Java代碼在Android中實(shí)現(xiàn)圖片裁剪功能
這篇文章主要介紹了使用Java代碼在Android中實(shí)現(xiàn)圖片裁剪功能,許多應(yīng)用都需要此類從相冊中選取圖片然后編輯的功能,需要的朋友可以參考下2015-07-07
Android利用animation-list實(shí)現(xiàn)幀動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了Android利用animation-list實(shí)現(xiàn)幀動(dòng)畫,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Android關(guān)鍵字persistent詳細(xì)分析
這篇文章主要介紹了Android關(guān)鍵字persistent的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-04-04
Android 快速使用正則表達(dá)式,校驗(yàn)身份證號的實(shí)例
下面小編就為大家分享一篇Android 快速使用正則表達(dá)式,校驗(yàn)身份證號的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Android MenuItem 自定義長按事件的實(shí)現(xiàn)
這篇文章主要介紹了Android MenuItem 自定義長按事件的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
Android Studio提示inotify大小不足的解決辦法
大家在使用Android Studio導(dǎo)入AOSP源碼的時(shí)候,可能會(huì)遇到inotify大小不足的問題,這篇文章就給大家介紹了怎么解決這個(gè)問題的方法,有需要的朋友們可以參考借鑒。2016-09-09
Android開源框架的SlidingFragment的使用示例
今天小編就為大家分享一篇關(guān)于Android開源框架的SlidingFragment的使用示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03
Android代碼實(shí)現(xiàn)AdapterViews和RecyclerView無限滾動(dòng)
這篇文章主要為大家詳細(xì)介紹了Android代碼實(shí)現(xiàn)AdapterViews和RecyclerView無限滾動(dòng)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07

