Android中發(fā)送Http請求(包括文件上傳、servlet接收)的實例代碼
/**
* 通過http協(xié)議提交數(shù)據(jù)到服務(wù)端,實現(xiàn)表單提交功能,包括上傳文件
* @param actionUrl 上傳路徑
* @param params 請求參數(shù) key為參數(shù)名,value為參數(shù)值
* @param file 上傳文件
*/
public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {
try {
PostMethod post = new PostMethod(actionUrl);
List<art> formParams = new ArrayList<art>();
for(Map.Entry<String, String> entry : params.entrySet()){
formParams.add(new StringPart(entry.getKey(), entry.getValue()));
}
if(files!=null)
for(FormBean file : files){
//filename為在服務(wù)端接收時希望保存成的文件名,filepath是本地文件路徑(包括了源文件名),filebean中就包含了這倆屬性
formParams.add(new FilePart("file", file.getFilename(), new File(file.getFilepath())));
}
Part[] parts = new Part[formParams.size()];
Iterator<art> pit = formParams.iterator();
int i=0;
while(pit.hasNext()){
parts[i++] = pit.next();
}
//如果出現(xiàn)亂碼可以嘗試一下方式
//StringPart sp = new StringPart("TEXT", "testValue", "GB2312");
//FilePart fp = new FilePart("file", "test.txt", new File("./temp/test.txt"), null, "GB2312"
//postMethod.getParams().setContentCharset("GB2312");
MultipartRequestEntity mrp = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(mrp);
//execute post method
HttpClient client = new HttpClient();
int code = client.executeMethod(post);
System.out.println(code);
} catch ...
}
通過以上代碼可以成功的模擬java客戶端發(fā)送post請求,服務(wù)端也能接收并保存文件
java端測試的main方法:
public static void main(String[] args){
String actionUrl = "http://192.168.0.123:8080/WSserver/androidUploadServlet";
Map<String, String> strParams = new HashMap<String, String>();
strParams.put("paramOne", "valueOne");
strParams.put("paramTwo", "valueTwo");
FormBean[] files = new FormBean[]{new FormBean("dest1.xml", "F:/testpostsrc/main.xml")};
HttpTool.postMultiParams(actionUrl,strParams,files);
}
本以為大功告成了,結(jié)果一移植到android工程中,編譯是沒有問題的。
但是運行時拋了異常 先是說找不到PostMethod類,org.apache.commons.httpclient.methods.PostMethod這個類絕對是有包含的;
還有個異常就是VerifyError。 開發(fā)中有幾次碰到這個異常都束手無策,覺得是SDK不兼容還是怎么地,哪位知道可得跟我說說~~
于是看網(wǎng)上有直接分析http request的內(nèi)容構(gòu)建post請求的,也有找到帶上傳文件的,拿下來運行老是有些問題,便直接通過運行上面的java工程發(fā)送的post請求,在servlet中打印出請求內(nèi)容,然后對照著拼接字符串和流終于給實現(xiàn)了!代碼如下:
***********************************************************
/**
* 通過拼接的方式構(gòu)造請求內(nèi)容,實現(xiàn)參數(shù)傳輸以及文件傳輸
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String 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);
// 首先組拼文本類型的參數(shù)
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());
// 發(fā)送文件數(shù)據(jù)
if(files!=null)
for (Map.Entry<String, File> file: files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
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());
}
//請求結(jié)束標(biāo)志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到響應(yīng)碼
int res = conn.getResponseCode();
if (res == 200) {
InputStream 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();
}
**********************
button響應(yīng)中的代碼:
**********************
public void onClick(View v){
String actionUrl = getApplicationContext().getString(R.string.wtsb_req_upload);
Map<String, String> params = new HashMap<String, String>();
params.put("strParamName", "strParamValue");
Map<String, File> files = new HashMap<String, File>();
files.put("tempAndroid.txt", new File("/sdcard/temp.txt"));
try {
HttpTool.postMultiParams(actionUrl, params, files);
} catch ...
***************************
服務(wù)器端servlet代碼:
***************************
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//print request.getInputStream to check request content
//HttpTool.printStreamContent(request.getInputStream());
RequestContext req = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(req)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setFileSizeMax(FILE_MAX_SIZE);
List items = new ArrayList();
try {
items = fileUpload.parseRequest(request);
} catch ...
Iterator it = items.iterator();
while(it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+new String(fileItem.getString().getBytes("ISO-8859-1"),"GBK"));
} else {
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+
fileItem.isInMemory()+" "+fileItem.getContentType()+" "+fileItem.getSize());
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
File newFile = new File(FILE_SAVE_PATH+fullFile.getName());
try {
fileItem.write(newFile);
} catch ...
} else {
System.out.println("no file choosen or empty file");
}
}
}
}
}
public void init() throws ServletException {
//讀取在web.xml中配置的init-param
FILE_MAX_SIZE = Long.parseLong(this.getInitParameter("file_max_size"));//上傳文件大小限制
FILE_SAVE_PATH = this.getInitParameter("file_save_path");//文件保存位置
}
- android文件上傳示例分享(android圖片上傳)
- android 上傳文件到服務(wù)器代碼實例
- Android OkHttp Post上傳文件并且攜帶參數(shù)實例詳解
- Android實現(xiàn)上傳文件功能的方法
- android選擇視頻文件上傳到后臺服務(wù)器
- Android基于Http協(xié)議實現(xiàn)文件上傳功能的方法
- Android中實現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度
- Android Retrofit實現(xiàn)多圖片/文件、圖文上傳功能
- Android實現(xiàn)上傳文件到服務(wù)器實例詳解
- android通過servlet上傳文件到服務(wù)器
相關(guān)文章
Android布局ConstraintLayout代碼修改約束及輔助功能
這篇文章主要為大家介紹了Android布局ConstraintLayout代碼修改約束及輔助功能示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Android編程之ListPreference用法實例分析
這篇文章主要介紹了Android編程之ListPreference用法,結(jié)合實例形式較為詳細(xì)的分析說明了ListPreference的功能、用法及相關(guān)注意事項,需要的朋友可以參考下2015-12-12
Android開源項目PullToRefresh下拉刷新功能詳解2
這篇文章主要為大家進(jìn)一步的介紹了Android開源項目PullToRefresh下拉刷新功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
Android中的SpannableString與SpannableStringBuilder詳解
這篇文章主要給大家介紹了關(guān)于Android中SpannableString與SpannableStringBuilder的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10
android TextView不用ScrollViewe也可以滾動的方法
這篇文章主要介紹了android TextView不用ScrollViewe也可以滾動的方法,很簡單實用的代碼,大家參考使用吧2013-11-11

