Android編程使用HTTP協(xié)議與TCP協(xié)議實(shí)現(xiàn)上傳文件的方法
本文實(shí)例講述了Android編程使用HTTP協(xié)議與TCP協(xié)議實(shí)現(xiàn)上傳文件的方法。分享給大家供大家參考,具體如下:
Android上傳文件有兩種方式,第一種是基于Http協(xié)議的HttpURLConnection,第二種是基于TCP協(xié)議的Socket。 這兩種方式的區(qū)別是使用HttpURLConnection上傳時(shí)內(nèi)部有緩存機(jī)制,如果上傳較大文件會(huì)導(dǎo)致內(nèi)存溢出。如果用TCP協(xié)議Socket方式上傳就會(huì)解決這種弊端。
HTTP協(xié)議HttpURLConnection
1. 通過URL封裝路徑打開一個(gè)HttpURLConnection
2.設(shè)置請(qǐng)求方式以及頭字段:Content-Type、Content-Length、Host
3.拼接數(shù)據(jù)發(fā)送
示例:
private static final String BOUNDARY = "---------------------------7db1c523809b2";//數(shù)據(jù)分割線
public boolean uploadHttpURLConnection(String username, String password, String path) throws Exception {
//找到sdcard上的文件
File file = new File(Environment.getExternalStorageDirectory(), path);
//仿Http協(xié)議發(fā)送數(shù)據(jù)方式進(jìn)行拼接
StringBuilder sb = new StringBuilder();
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");
sb.append("\r\n");
sb.append(username + "\r\n");
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");
sb.append("\r\n");
sb.append(password + "\r\n");
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");
sb.append("Content-Type: image/pjpeg" + "\r\n");
sb.append("\r\n");
byte[] before = sb.toString().getBytes("UTF-8");
byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL("http://192.168.1.16:8080/14_Web/servlet/LoginServlet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length", String.valueOf(before.length + file.length() + after.length));
conn.setRequestProperty("HOST", "192.168.1.16:8080");
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(file);
out.write(before);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(after);
in.close();
out.close();
return conn.getResponseCode() == 200;
}
TCP協(xié)議Socket
1.我們可以使用Socket發(fā)送TCP請(qǐng)求,將上傳數(shù)據(jù)分段發(fā)送
示例:
public boolean uploadBySocket(String username, String password, String path) throws Exception {
// 根據(jù)path找到SDCard中的文件
File file = new File(Environment.getExternalStorageDirectory(), path);
// 組裝表單字段和文件之前的數(shù)據(jù)
StringBuilder sb = new StringBuilder();
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");
sb.append("\r\n");
sb.append(username + "\r\n");
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");
sb.append("\r\n");
sb.append(password + "\r\n");
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + path + "\"" + "\r\n");
sb.append("Content-Type: image/pjpeg" + "\r\n");
sb.append("\r\n");
// 文件之前的數(shù)據(jù)
byte[] before = sb.toString().getBytes("UTF-8");
// 文件之后的數(shù)據(jù)
byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL("http://192.168.1.199:8080/14_Web/servlet/LoginServlet");
// 由于HttpURLConnection中會(huì)緩存數(shù)據(jù), 上傳較大文件時(shí)會(huì)導(dǎo)致內(nèi)存溢出, 所以我們使用Socket傳輸
Socket socket = new Socket(url.getHost(), url.getPort());
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true, "UTF-8");
// 寫出請(qǐng)求頭
ps.println("POST /14_Web/servlet/LoginServlet HTTP/1.1");
ps.println("Content-Type: multipart/form-data; boundary=" + BOUNDARY);
ps.println("Content-Length: " + String.valueOf(before.length + file.length() + after.length));
ps.println("Host: 192.168.1.199:8080");
InputStream in = new FileInputStream(file);
// 寫出數(shù)據(jù)
out.write(before);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(after);
in.close();
out.close();
return true;
}
搭建服務(wù)器,完成上傳功能
package cn.test.web.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
File dir = new File(request.getSession().getServletContext().getRealPath("/WEB-INF/upload"));
//創(chuàng)建目錄
dir.mkdir();
for (FileItem item : items)
if (item.isFormField())
System.out.println(item.getFieldName() + ": " + item.getString());
else{
item.write(new File(dir,item.getName().substring(item.getName().lastIndexOf("\\")+1)));
}
} catch (Exception e) {
e.printStackTrace();
}
else {
System.out.println(request.getMethod());
System.out.println(request.getParameter("username"));
System.out.println(request.getParameter("password"));
}
}
}
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Java URL自定義私有網(wǎng)絡(luò)協(xié)議
- SQL Server 2008網(wǎng)絡(luò)協(xié)議深入理解
- Getmac返回計(jì)算機(jī)中所有網(wǎng)卡的媒體訪問控制 (MAC) 地址以及每個(gè)地址的網(wǎng)絡(luò)協(xié)議列表
- winsockfix網(wǎng)絡(luò)協(xié)議修復(fù)工具
- TCP協(xié)議詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- python3實(shí)現(xiàn)TCP協(xié)議的簡單服務(wù)器和客戶端案例(分享)
- C#基于TCP協(xié)議的服務(wù)器端和客戶端通信編程的基礎(chǔ)教程
- 使用C語言編寫基于TCP協(xié)議的Socket通訊程序?qū)嵗窒?/a>
- Java基于Tcp協(xié)議的socket編程實(shí)例
- .Net WInform開發(fā)筆記(二)Winform程序運(yùn)行結(jié)構(gòu)圖及TCP協(xié)議在Winform中的應(yīng)用
- Packetdrill的簡明使用手冊
相關(guān)文章
Android Studio 4.0 正式發(fā)布在Ubuntu 20.04中安裝的方法
這篇文章主要介紹了Android Studio 4.0 正式發(fā)布如何在Ubuntu 20.04中安裝,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
Android入門之Gallery+ImageSwitcher用法實(shí)例解析
這篇文章主要介紹了Android入門之Gallery+ImageSwitcher用法,對(duì)Android初學(xué)者有很好的參考借鑒價(jià)值,需要的朋友可以參考下2014-08-08
Android中實(shí)現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度
本篇文章主要介紹了Android中實(shí)現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android 啟動(dòng)另一個(gè)App/apk中的Activity實(shí)現(xiàn)代碼
這篇文章主要介紹了Android 啟動(dòng)另一個(gè)App/apk中的Activity實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04
kotlin object關(guān)鍵字單例模式實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了kotlin object關(guān)鍵字單例模式實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Android 實(shí)現(xiàn)關(guān)機(jī)的多種方式
有段時(shí)間做系統(tǒng)hook時(shí)需要用到系統(tǒng)重啟,找了幾種重啟的方法,還有幾種關(guān)機(jī)的方法,總結(jié)一下,有此需求的同學(xué)可以選擇適合自己的方式2021-05-05

