java(android)客户端post方式上传多图片至服务器

来源:互联网 发布:数据库的英文单词 编辑:程序博客网 时间:2024/05/29 04:45
最近在处理项目中(android)客户端上传图片给服务端的问题,下面是我的一点拙见,查阅了不少资料,百变不离其宗,都是在客户端编辑一个请求头,即是模仿浏览器发包,我们使用浏览器的开发工具->网络(现在大部分浏览器都有)很容易截到发送和接收的包。下面是我通过火狐的开发工具截到的包。我想通过图片来和代码对比,更容易理解,上传多图片是什么回事(其实理解了原理,传参数,或者参数和图片一起也不难了)。同时,由图中JSESSIONID可知,我们也可以设置它,来保持session会话(在禁cookie,或无cookie时,不失为好方法)。

post请求截包图`

package com.http.post;​

import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.UUID;

import org.junit.Test;

public class uplad {

private String
actionUrl=”服务器URL”;
//图中的filename属性
private String newName=”Chrysanthemum.jpg”;
//上传图片本地路径
private String[]filePath={“C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg”,

“C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg”};

// @Test

public void uploadFile() {

String end = “\r\n”;

String twoHyphens = “–”;
//随机生成边界编码如图中———–183741.……
String boundary = “—————————–”+UUID.randomUUID().toString();

try {

URL url = new URL(actionUrl);

HttpURLConnection con = (HttpURLConnection) url.openConnection();
/*
在编辑包,一定要按如图中的显示格式编辑
*/
//设置请求头,有些没有设置,它自身有默认值,具体看javaAPI
con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

con.setRequestMethod(“POST”);

con.setRequestProperty(“Connection”, “Keep-Alive”);

con.setRequestProperty(“Charset”, “UTF-8”);
//图片必须设置content-type:multipart/form-data;
con.setRequestProperty(“Content-Type”,

“multipart/form-data;boundary=” + boundary);
//请求头设置结束
//设置请求体,post提交的内容
DataOutputStream ds = new DataOutputStream(con.getOutputStream());

FileInputStream fStream = null;

for (String uploadFile : filePath) { //多张图片
/*
看图可知格式,
首先以—-*
再到Content-Disposition,
再到Content-Type
最后 post的内容,不同内容格式不一样,可行截包研究
*/
ds.writeBytes(twoHyphens + boundary + end);
/*
name就是html中中的name(很关键,服务端通过它(key)来识别接收),newName就是value。
*/
ds.writeBytes(“Content-Disposition: form-data; “

  • “name=\”upload\”;filename=\”” + newName + “\”” +end+

“Content-Type:image/jpeg”+ end);

ds.writeBytes(end);
//请求体头部设置结束,一下是内容,图中的乱码

try {

fStream = new FileInputStream(uploadFile);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

int bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

int length = -1;

while ((length = fStream.read(buffer)) != -1) {

ds.write(buffer, 0, length);

}

ds.writeBytes(end);

}
/*
请求体结束,格式——–**
这个图中没能显示,可自行截包看看
*/
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

fStream.close();

ds.flush();

InputStream is = con.getInputStream();//接收响应

int ch;

StringBuffer b = new StringBuffer();

while ((ch = is.read()) != -1) {

b.append((char) ch);

}

System.out.println(“上传成功” + b.toString().trim());

ds.close();

} catch (Exception e) {

System.out.println(“上传失败” + e);

}

}

}
这文章本人一点心得,表达一般,不知道理解没有欢迎指正,若说还有其他更好方法,不吝赐教,欢迎交流,共同进步。

1 0