httpclient4上传文件|commons-httpclient如何实现文件上传

『壹』 httpclient 4 + servlet上传

public class TestServlets extends HttpServlet{private String uploadPath = "D:\\temp"; // 上传文件的目录 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录 File tempPathFile; public void init() throws ServletException { File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } }public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);// 得到所有的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } System.out.print("upload succeed"); } catch (Exception e) { System.out.println(e.getMessage()); // 可以跳转出错页面 e.printStackTrace(); }}}

『贰』 android的自带的httpClient 怎么上传文件

在Android开发中,Android SDK附带了Apache的HttpClient,它是一个完善的客户端。它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执行HTTP GET和HTTP POST调用。

HTTP工作原理:

1.客户端(一般是指浏览器,这里是指自己写的程序)与服务器建立连接

2.建立连接后,客户端向服务器发送请求

3.服务器接收到请求后,向客户端发送响应信息

4.客户端与服务器断开连接

HttpClient的一般使用步骤:

1.使用DefaultHttpClient类实例化HttpClient对象

2.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

3.调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

4.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

最后记得要在AndroidManifest.xml文件添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

附件中包含了一个拍照上传的源代码

『叁』 如何接收httpclient 文件上传

一般的情况下我们都来是使用Chrome或者其他浏自览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据、文件上传下载等等。所访问的这些页面有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如H

『肆』 httpclient如何一起上传内容和图片

以文件的形式传参/** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param actionUrl 访问的服务器URL * @param params 普通参数 * @param files 文件参数 * @return * @throws IOException */ public static void 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()); InputStream in = null; // 发送文件数据 if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); // name是post中传参的键 filename是文件的名称 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) { 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(); }以数据流的形式传参public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files) throws Exception { StringBuilder sb2 = null; 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(6 * 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()); InputStream in = null; // 发送文件数据 if (files != null) { for (Map.Entry<String, byte[]> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"pic\"; 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(file.getValue()); 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) { in = conn.getInputStream(); int ch; sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } System.out.println(sb2.toString()); } outStream.close(); conn.disconnect(); // 解析服务器返回来的数据 return Parsejson.getEditMadIconResult(sb2.toString()); } else { return "Update icon Fail"; } // return in.toString(); }

『伍』 如何获得一个文件的上传与Apache HttpClient的4进度条

1. 我介绍一个派生FileEntity只是计数写入的字节。OutputStreamProgress做了实际的计数(一种装饰器的实际OutputStream)。 这样做的好处(与装修一般)是,我不需要从文件流复制的实际就像实际的复制到输出流。我也可以改变一个不同的(新)之类的NFileEntity。 享受… FileEntity.javapublic class FileEntity extends org.apache.http.entity.FileEntity { private OutputStreamProgress outstream; public FileEntity(File file, String contentType) { super(file, contentType); } @Override public void writeTo(OutputStream outstream) throws IOException { this.outstream = new OutputStreamProgress(outstream); super.writeTo(this.outstream); } /** * Progress: 0-100 */ public int getProgress() { if (outstream == null) { return 0; } long contentLength = getContentLength(); if (contentLength <= 0) { // Prevent division by zero and negative values return 0; } long writtenLength = outstream.getWrittenLength(); return (int) (100*writtenLength/contentLength); }}OutputStreamProgress.javapublic class OutputStreamProgress extends OutputStream { private final OutputStream outstream; private volatile long bytesWritten=0; public OutputStreamProgress(OutputStream outstream) { this.outstream = outstream; } @Override public void write(int b) throws IOException { outstream.write(b); bytesWritten++; } @Override public void write(byte[] b) throws IOException { outstream.write(b); bytesWritten += b.length; } @Override public void write(byte[] b, int off, int len) throws IOException { outstream.write(b, off, len); bytesWritten += len; } @Override public void flush() throws IOException { outstream.flush(); } @Override public void close() throws IOException { outstream.close(); } public long getWrittenLength() { return bytesWritten; }}

『陆』 commons-httpclient如何实现文件上传

在struts2中结合HttpClient进行文件上传最近遇到了用httpclient进行上传文件的问题,下面我就和大家简单的说一下:package com.imps.action;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.List;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.PostMethod;public class TabinfoAction extends BaseAction{private File[] myFile;private String[] myFileFileName;// 文件名private Integer[] myFileFileSize;// 文件大小private String[] myFileContentType;// 文件类型public String uploadPost(){String posturl ="http://127.0.0.1:8080/settabimage.aspx";System.out.println(posturl);String status=null;for(int i=0;i<myFile.length;i++){FileInputStream file=new FileInputStream(myFile[i]);InputStream in = new BufferedInputStream(file);PostMethod post=new PostMethod(posturl);post.setRequestBody(in);HttpClient client = new HttpClient();client.executeMethod(post);String response=new String(post.getResponseBodyAsString().getBytes("ISO-8859-1"),"UTF-8");post.releaseConnection();in.close();file.close();}}public File[] getMyFile() {return myFile;}public void setMyFile(File[] myFile) {this.myFile = myFile;}public String[] getMyFileFileName() {return myFileFileName;}public void setMyFileFileName(String[] myFileFileName) {this.myFileFileName = myFileFileName;}public Integer[] getMyFileFileSize() {return myFileFileSize;}public void setMyFileFileSize(Integer[] myFileFileSize) {this.myFileFileSize = myFileFileSize;}public String[] getMyFileContentType() {return myFileContentType;}public void setMyFileContentType(String[] myFileContentType) {this.myFileContentType = myFileContentType;}千万记住不要记忘记关闭流和释放http连接

『柒』 httpclient 怎么实现多文件上传 c/s java

虽然在JDK的java.net包中已经提供了访问HTTP协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。以下是简单的post例子:Stringurl="bbslogin2.php";PostMethodpostMethod=newPostMethod(url);//填入各个表单域的值NameValuePair[]data={newNameValuePair("id","youUserName"),newNameValuePair("passwd","yourPwd")};//将表单的值放入postMethod中postMethod.setRequestBody(data);//执行postMethodintstatusCode=httpClient.executeMethod(postMethod);//HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发//301或者302if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY){//从头中取出转向的地址HeaderlocationHeader=postMethod.getResponseHeader("location");Stringlocation=null;if(locationHeader!=null){location=locationHeader.getValue();System.out.println("Thepagewasredirectedto:"+location);}else{System.err.println("Locationfieldvalueisnull.");}return;}详情见:/developerworks/cn/opensource/os-httpclient/

『捌』 apache httpclient4怎么实现同时上传多个文件

1.服务器认证(Server Authentication) HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以通过 setCredentials(String realm, Credentials cred)和getCredentialapache httpclient4怎么实现同时上传多个文件

『玖』 apache httpclient4怎么实现同时上传多个文件

1.服务器认证(Server Authentication)HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以通过 setCredentials(String realm, Credentials cred)和getCredentials(String realm)来获取或设置。HttpClient内建的自动认证,可以通过HttpMethod类的setDoAuthentication(boolean doAuthentication)方法关闭,而且这次关闭只影响HttpMethod当前的实例。2.代理认证(proxy authentication)除了登录信息需单独存放以外,代理认证与服务器认证几乎一致。用 setProxyCredentials(String realm, Credentials cred)和 getProxyCredentials(String realm)设、取登录信息。3.认证方案(authentication schemes)是HTTP中规定最早的也是最兼容的方案,遗憾的是也是最不安全的一个方案,因为它以明码传送用户名和密码。它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。

『拾』 HTTPclient使用MultipartEntity怎么上传文件

你先搞清楚 HTTPclient 是做什么用的HTTPclient 的作用是在 jsp 中模拟一个浏览器,即 HTTP 协议的客户端(client)专你的后台代码是属将你本地服务器上的文件像浏览器那样上传到目标服务器于是 new File("C:\\1.txt") 的问题就可以解决了吧?C:\\1.txt 是你本地服务器中的文件,当然文件名是你自己定的至于 multipart/form-data 声明,那是由 HttpPost 的参数 MultipartEntity 自动加上的


赞 (0)