Android中发送Http恳求实例(包含文件上传、servlet接管)
添加时间:2013-5-25 点击量:
起首我是写了个java测试发送post恳求:可以包含文本参数和文件参数
- /
- 经由过程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, String> params,
- 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, 0, 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));
- }
- 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 ...
- }
- 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);//文件保存地位
- }
我们永远不要期待别人的拯救,只有自己才能升华自己。自己已准备好了多少容量,方能吸引对等的人与我们相遇,否则再美好的人出现、再动人的事情降临身边,我们也没有能量去理解与珍惜,终将擦肩而过。—— 姚谦《品味》
起首我是写了个java测试发送post恳求:可以包含文本参数和文件参数
- /
- 经由过程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, String> params,
- 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, 0, 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));
- }
- 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 ...
- }
- 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);//文件保存地位
- }