本人最近在安卓端开发与后台链接的代码,但是我发现在安卓中没有提供上传表单的方式。于是我上网了解了一下,了解到可以应用一种向后台写入的特殊格式可以达到上传表单的效果。可惜的是调试未成功,让人纠结的是程序没有报错。现在贴出代码,希望大家帮一下忙。
这是网页的代码:
<form action="/home/add" method="post" enctype="multipart/form-data"> <table> <tr> <td>标题:</td> <td> <input type="text" name="title"/> </td> </tr> <tr> <td>body:</td> <td> <textarea style="height: 150px;width:300px;resize: none" name="body" ></textarea></td> </tr> <tr> <td>文件</td> <td> <input type="file" name="img"/> </td> </tr> <tr> <td></td> <td> <input type="submit" class="btn btn-primary" value="提交"/> </td> </tr> </table> </form>
这是android里面的代码:
final String BOUNDARY="===================";
final String HYPHENS="--";
final String CRLF="\r\n";
URL url=new URL(UPLOAD_ONE_RES);
HttpURLConnection connect=(HttpURLConnection)url.openConnection();
connect.setRequestMethod("POST");
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setUseCaches(false);
connect.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
DataOutputStream dataOut=new DataOutputStream(connect.getOutputStream());
dataOut.writeBytes(HYPHENS+BOUNDARY+CRLF);
//写图片
String strContentDisposition="Content-Disposition: form-data; name=\"img\"; filename=\""+imgName+".jpg"+"\"";
String strContentType="Content-Type: image/jpeg";
dataOut.writeBytes(strContentDisposition+CRLF);
dataOut.writeBytes(strContentType+CRLF);
dataOut.writeBytes(CRLF);
FileInputStream fileInput=new FileInputStream(imgFile);
byte[] data=new byte[fileInput.available()];
fileInput.read(data);
dataOut.write(data);
dataOut.writeBytes(CRLF);
dataOut.writeBytes(HYPHENS+BOUNDARY+CRLF);
fileInput.close();
//title
String strContentDisposition_title="Content-Disposition: form-data; name=\"title\"";
String strContentType_title="Content-Type: text";
dataOut.writeBytes(strContentDisposition_title+CRLF);
dataOut.writeBytes(strContentType_title+CRLF);
dataOut.writeBytes(CRLF);
dataOut.writeBytes(title);
dataOut.writeBytes(CRLF);
dataOut.writeBytes(HYPHENS+BOUNDARY+CRLF);
//body
String strContentDisposition_body="Content-Disposition: form-data; name=\"body\"";
String strContentType_body="Content-Type: text";
dataOut.writeBytes(strContentDisposition_body+CRLF);
dataOut.writeBytes(strContentType_body+CRLF);
dataOut.writeBytes(CRLF);
dataOut.writeBytes(content);
dataOut.writeBytes(CRLF);
dataOut.writeBytes(HYPHENS+BOUNDARY+CRLF);
//读写结束
dataOut.flush();
dataOut.close(); 程序运行的时候没有报错,但是数据并没有上传到后台中去。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
apachehttpclient很好用,android默认就有。要是想上传文件,加个mime包就ok
用HttpPost多好
可以啊,用HttpEntity类。用HttpPost可以达到上传表单的效果么?