HttpClient通过Post上传文件的实例代码
程序员文章站
2024-03-06 17:52:38
在之前一段的项目中,使用java模仿http post方式发送参数以及文件,单纯的传递参数或者文件可以使用urlconnection进行相应的处理。
但是项目中涉及到既要...
在之前一段的项目中,使用java模仿http post方式发送参数以及文件,单纯的传递参数或者文件可以使用urlconnection进行相应的处理。
但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递xml文件)。在网上寻找之后,发现是使用httclient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用httpclient时,不能使用request.getparameter()对普通参数进行获取,而要在服务器端使用upload来进行操作。
httpclient4.2 jar下载 :
客户端代码:
import java.io.bytearrayoutputstream; import java.io.file; import java.io.ioexception; import java.io.inputstream; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.httpstatus; import org.apache.http.parseexception; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.entity.mime.multipartentity; import org.apache.http.entity.mime.content.filebody; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.util.entityutils; /** * * @author <a href="mailto:just_szl@hotmail.com"> geray</a> * @version 1.0,2012-6-12 */ public class httppostargumenttest2 { //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径 public void submitpost(string url,string filename1,string filename2, string filepath){ httpclient httpclient = new defaulthttpclient(); try { httppost httppost = new httppost(url); filebody bin = new filebody(new file(filepath + file.separator + filename1)); filebody bin2 = new filebody(new file(filepath + file.separator + filename2)); stringbody comment = new stringbody(filename1); multipartentity reqentity = new multipartentity(); reqentity.addpart("file1", bin);//file1为请求后台的file upload;属性 reqentity.addpart("file2", bin2);//file2为请求后台的file upload;属性 reqentity.addpart("filename1", comment);//filename1为请求后台的普通参数;属性 httppost.setentity(reqentity); httpresponse response = httpclient.execute(httppost); int statuscode = response.getstatusline().getstatuscode(); if(statuscode == httpstatus.sc_ok){ system.out.println("服务器正常响应....."); httpentity resentity = response.getentity(); system.out.println(entityutils.tostring(resentity));//httpclient自带的工具类读取返回数据 system.out.println(resentity.getcontent()); entityutils.consume(resentity); } } catch (parseexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } finally { try { httpclient.getconnectionmanager().shutdown(); } catch (exception ignore) { } } } /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub httppostargumenttest2 httppostargumenttest2 = new httppostargumenttest2(); httppostargumenttest2.submitpost("http://127.0.0.1:8080/demo/receivedata.do", "test.xml","test.zip","d://test"); } }
服务端代码:
public void receivedata(httpservletrequest request, httpservletresponse response) throws appexception{ printwriter out = null; response.setcontenttype("text/html;charset=utf-8"); map map = new hashmap(); fileitemfactory factory = new diskfileitemfactory(); servletfileupload upload = new servletfileupload(factory); file directory = null; list<fileitem> items = new arraylist(); try { items = upload.parserequest(request); // 得到所有的文件 iterator<fileitem> it = items.iterator(); while (it.hasnext()) { fileitem fitem = (fileitem) it.next(); string fname = ""; object fvalue = null; if (fitem.isformfield()) { // 普通文本框的值 fname = fitem.getfieldname(); // fvalue = fitem.getstring(); fvalue = fitem.getstring("utf-8"); map.put(fname, fvalue); } else { // 获取上传文件的值 fname = fitem.getfieldname(); fvalue = fitem.getinputstream(); map.put(fname, fvalue); string name = fitem.getname(); if(name != null && !("".equals(name))) { name = name.substring(name.lastindexof(file.separator) + 1); // string stamp = stringutils.getformattedcurrdatenumberstring(); string timestamp_str = timeutils.getcurryearyyyy(); directory = new file("d://test"); directory.mkdirs(); string filepath = ("d://test")+ timestamp_str+ file.separator + name; map.put(fname + "filepath", filepath); inputstream is = fitem.getinputstream(); fileoutputstream fos = new fileoutputstream(filepath); byte[] buffer = new byte[1024]; while (is.read(buffer) > 0) { fos.write(buffer, 0, buffer.length); } fos.flush(); fos.close(); map.put(fname + "filename", name); } } } } catch (exception e) { system.out.println("读取http请求属性值出错!"); // e.printstacktrace(); logger.error("读取http请求属性值出错"); } // 数据处理 try { out = response.getwriter(); out.print("{success:true, msg:'接收成功'}"); out.close(); } catch (ioexception e) { e.printstacktrace(); } }
以上所述是小编给大家介绍的httpclient通过post上传文件的实例代码,希望对大家有所帮助
推荐阅读
-
Android 通过httppost上传文本文件到服务器的实例代码
-
HttpClient通过Post上传文件的实例代码
-
Android 通过httppost上传文本文件到服务器的实例代码
-
C#实现Web文件上传的两种方法实例代码
-
silverlight用webclient大文件上传的实例代码
-
C#实现Web文件上传的两种方法实例代码
-
asp.net实现上传文件显示本地绝对路径的实例代码
-
webuploader在springMVC+jquery+Java开发环境下的大文件分片上传的实例代码
-
silverlight用webclient大文件上传的实例代码
-
Struts2 文件上传进度条的实现实例代码