复制代码 代码如下:
/**
* 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件
* @param actionUrl 上传路径
* @param params 请求参数 key为参数名,value为参数值
* @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为在服务端接收时希望保存成的文件名,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();
}
//如果出现乱码可以尝试一下方式
//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客户端发送post请求,服务端也能接收并保存文件
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);
}
本以为大功告成了,结果一移植到androID工程中,编译是没有问题的。
但是运行时抛了异常 先是说找不到PostMethod类,org.apache.commons.httpclIEnt.methods.PostMethod这个类绝对是有包含的;
还有个异常就是VerifyError。 开发中有几次碰到这个异常都束手无策,觉得是SDK不兼容还是怎么地,哪位知道可得跟我说说~~
于是看网上有直接分析http request的内容构建post请求的,也有找到带上传文件的,拿下来运行老是有些问题,便直接通过运行上面的java工程发送的post请求,在servlet中打印出请求内容,然后对照着拼接字符串和流终于给实现了!代码如下:
***********************************************************
复制代码 代码如下:
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl,
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);
// 首先组拼文本类型的参数
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());
// 发送文件数据
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,len);
}
is.close();
outStream.write(liNEND.getBytes());
}
//请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + liNEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
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响应中的代码:
**********************
复制代码 代码如下:
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 ...
***************************
服务器端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中发送Http请求(包括文件上传、servlet接收)的实例代码全部内容,希望文章能够帮你解决Android中发送Http请求(包括文件上传、servlet接收)的实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)