Android 通过post上传文件--HttpURLConnection实现

最近在做向服务器提交文件,本来用的xutils,使用起来挺简单,代码超不过10行,但是想深入了解一下原理,所以就自己用HttpURLConnection实现文件的上传。

无论是浏览器通过表单提交文件,还是APP通过post提交,其实原理都是一样的。APP只要仿照浏览器的表单提交数据的样式去提交文件,服务器就可以解析并处理文件。

那就首先来看一下浏览器提交的数据样式和请求头的信息。

HTML核心代码:

<form method="post" action="http://192.168.218.163:8080/Test/FileUpLoad" enctype="multipart/form-data">
<input type="file" name="file" size="20" ><br/>
<input type="submit" name="submit" value="提交">
</form>

请求的头部信息:

host:192.168.218.163:8080

connection:keep-alive

content-length:432

cache-control:max-age=0

origin:null

upgrade-insecure-requests:1

user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

content-type:multipart/form-data; boundary=----WebKitFormBoundarymYCoIxqCv49mE4Ok

accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

accept-encoding:gzip, deflate

accept-language:zh-CN,zh;q=0.8

cookie:__guid=158737658.212612550479137800.1501464417829.6194; monitor_count=15

头部信息的content-type是重点,如果是上传文件,表单的mime类型必须是multipart/form-data,“boundary”是用来隔开表单中不同部分数据的,它是由- -开头,而不是boundary数据开头,以- -结尾。

服务器获取到的数据:

------WebKitFormBoundarynug1Tk0jD0SCH33m

Content-Disposition: form-data; name="file"; filename="nuuid.ini"

Content-Type: application/octet-stream

 

##这是上传文件的数据##

------WebKitFormBoundarynug1Tk0jD0SCH33m--

上传文件,post出去的数据是比较严格的。数据必须以--boundary开头

每一条数据独占一行,内容描述信息样式:

Content-Disposition: form-data; name="file"; filename="nuuid.ini"

Content-Type: application/octet-stream

然后空一个空行(/r/n),再是具体的文件数据。然后- -boundary- -结尾。

下面开始写Java代码:

String uuid = UUID.randomUUID().toString();
        String BOUNDARY = uuid;
        String NewLine = "\r\n";
        String spec = "http://192.168.218.163:8080/Test/FileUpLoad";
        File file = new File("G:\\mv\\哥德巴赫猜想.txt");
        FileInputStream fis=null;
        DataOutputStream bos =null;
        DataInputStream bis=null;
URL url = new URL(spec);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			//打开输出
			connection.setDoOutput(true);
			//打开输入
			connection.setDoInput(true);
			//关闭缓存
			connection.setUseCaches(false);
			//读取超时
			connection.setReadTimeout(50*1000);
			//连接超时
			connection.setConnectTimeout(5*1000);
			//请求方式POST
			connection.setRequestMethod("POST");
			//设置请求头
//			connection.setRequestProperty("Connection", "Keep-Alive");
//connection.addRequestProperty("user-agent","Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; NX507J Build/KVT49L) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
			//必须设置,数据类型,编码方式,分界线
			connection.setRequestProperty("Content-Type", "multipart/form-data; charset=utf-8; boundary="+BOUNDARY);
//connection.setRequestProperty("accept-encoding","gzip"); 
			connection.setChunkedStreamingMode(1024 * 50);
			bos = new DataOutputStream(connection.getOutputStream());
			
			if (file.exists()) {
				fis = new FileInputStream(file);
				byte[]buff = new byte[1024];
				 bis = new DataInputStream(fis);
				int cnt=0;
				//数据以--BOUNDARY开始
				bos.write(("--"+BOUNDARY).getBytes());
				//换行
				bos.write(NewLine.getBytes());
				//内容描述信息
				content = "Content-Disposition: form-data; name=\""+filename+"\"; filename=\""+file.getName()+"\"";
				bos.write(content.getBytes());
				bos.write(NewLine.getBytes());
//				bos.write("Content-Type: application/octet-stream".getBytes());
//				bos.write(NewLine.getBytes());
//				bos.write("Content-Transfer-Encoding: binary".getBytes());
//				bos.write(NewLine.getBytes());
				bos.write(NewLine.getBytes());
            //空一行后,开始通过流传输文件数据
				while((cnt=bis.read(buff))!=-1){
					bos.write(buff,0,cnt);
				}
				bos.write(NewLine.getBytes());
				//结束标志--BOUNDARY--
				bos.write(("--"+BOUNDARY+"--").getBytes());
				bos.write(NewLine.getBytes());
				bos.flush();
			}
//开始发送请求,获取请求码和请求结果
			if (connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
				connection.getInputStream();
				System.out.println("url="+connection.getURL());
				BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String dat=null;
				while ((dat =read.readLine())!=null){
					System.out.println(dat);
				}
				System.out.println("请求成功");;
			}else {
				System.err.println("请求失败"+connection.getResponseMessage()+"code="+connection.getResponseCode());
			}

请求体的内容:

--32eeb4fb-7fe9-4fa3-a5bf-ec357c48a5d4

Content-Disposition: form-data; name="file"

Content-Type: text/plain; charset=utf-8

 

文本文件

--32eeb4fb-7fe9-4fa3-a5bf-ec357c48a5d4

Content-Disposition: form-data; name="哥德巴赫猜想.txt"; filename="哥德巴赫猜想.txt"

 

##上传文件的内容(文本或二进制)

--32eeb4fb-7fe9-4fa3-a5bf-ec357c48a5d4--

注:

1.post到服务器的数据格式要求严格,以--BOUNDARY开头,紧跟着是内容描述信息(Content-Disposition: form-data; name="filename"; filename=" ",然后空一行+内容正       文,--BOUNDARY--结尾。

2.注释的代码,是不必须的参数。

3.如果数据格式不按固定格式传输(描述信息和内容正文之间空一行),服务器在处理数据时会报Stream ended unexpectedly异常(服务器用的Apache FileUpload组件)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: HttpURLConnection 是 Java 的标准类库之一,可以用来发送 HTTP 请求。它支持 GET、POST、HEAD、OPTIONS、PUT、DELETE 和 TRACE 方法。可以使用 HttpURLConnection 类来发送 HTTP POST 请求。通常使用 HttpURLConnection 类发送 POST 请求时,需要设置请求头信息和请求参数。下面是一个示例代码: ``` URL url = new URL("http://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("param1=value1&param2=value2"); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { sb.append(lines); } System.out.println(sb.toString()); ``` 以上代码使用了 HttpURLConnection 发送一个 HTTP POST 请求,并设置了一些请求头信息(如 Content-Type)和请求参数。 注意:如果你在使用这个类发送请求时遇到了问题,请检查服务端是否支持该请求方法。 ### 回答2: HttpURLConnection Post是一种与服务器进行HTTP协议通信的方法。它是HttpURLConnection的子类,可以方便地发送POST请求并接收服务器响应。要使用HttpURLConnectionPOST方法,需要设置好URLConnection的请求属性,并根据需要写入请求正数据,并接收返回的响应数据。 具体实现流程如下: 1. 创建HttpURLConnection连接对象,并设置请求的URL地址。 2. 通过setRequestMethod()方法设置POST方式。 3. 设置URLConnection的一些请求属性,如请求超时时间、接收数据超时时间等。 4. 如果需要向服务器发送请求正数据,则需要在HttpURLConnection对象中开启输出流(setDoOutput(true))并写入正数据(如表单参数、JSON参数等)。 5. 向服务器发送请求,调用HttpURLConnection的connect()方法。 6. 接收服务器返回的响应数据,可以通过getInputStream()方法读取响应数据。 7. 如果要读取服务器返回的响应状态码、响应头信息等,可以通过HttpURLConnection提供的方法来获取。 使用HttpURLConnection Post方法要注意以下几点: 1. POST请求发送的参数需要绑定在请求正中,通过OutputStream将请求正发送给服务器。 2. 如果需要向服务器发送一个件,则可以使用multipart/form-data编码方式。 3. HttpsURLConnection是HttpURLConnection的子类,支持HTTPS请求。在发送HTTPS请求前需要配置SSLSocketFactory和HostnameVerifier。 总结来说,HttpURLConnection Post方法是一种比较简单易用的与服务器进行HTTP协议通信的方法,可以方便地发送POST请求并接收服务器响应。在实际开发中,如果要进行HTTP协议通信,建议选择使用HttpURLConnection Post方法。 ### 回答3: HttpURLConnectionAndroid 中的一个网络通信库,可以用来进行网络请求操作。其中,post 方法是 HttpURLConnection 中比较常用的一个方法。 post 方法的作用是向服务器提交数据。与 get 方法不同,post 方法不会将请求参数附加在 URL 中,而是将参数放在请求体中一并提交给服务器。这样设计的好处是可以避免 URL 过长,同时也可以保障数据的隐私性。 在使用 post 方法时,需要注意以下几个问题: 1. 设置请求方法:在创建 HttpURLConnection 对象之后,需要使用 setRequestMethod("POST") 方法将请求方法设置为 POST。 2. 设置请求头:在发送 post 请求之前,需要设置请求头,其中至少包含 Content-TypeContent-Length。Content-Type 指明请求体内容类型,微信支付时必须设置为 application/json。Content-Length 则指明请求体内容长度。 3. 设置请求体:用 OutputStream 向请求中写入需要提交的数据。 下面是一个 post 方法的示例代码: ``` URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", String.valueOf(postData.length())); OutputStream os = conn.getOutputStream(); os.write(postData.getBytes(StandardCharsets.UTF_8)); os.flush(); os.close(); int responseCode = conn.getResponseCode(); ``` 其中,url 表示请求的地址,postData 是需要提交的数据。 上述代码中,创建 HttpURLConnection 对象之后,我们首先使用 setRequestMethod 方法将请求方法设置为 POST,然后设置了两个请求头,最后将请求体写入到 outputstream 中。 执行完 write 方法之后,需要调用 flush 方法和 close 方法。其中 flush 方法是为了清空 buffer 缓存,将数据真正发送出去,close 方法是为了关闭输出流。 最后,使用 getResponseCode 方法获取服务器返回的状态码。根据不同的状态码,进行相应的处理即可。 总的来说,HttpURLConnection 中的 post 方法十分简单,只需要注意请求头和请求体的设置即可。在实际开发中,post 方法通常用于向服务器提交表单数据、上传、支付等一系列操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值