HttpClient通过Post上传文件的实例代码
在之前一段的项目中,使用Java模仿HttpPost方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。
但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递XML文件)。在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用Upload来进行操作。
HttpClient4.2jar下载:http://download.csdn.net/detail/just_szl/4370574
客户端代码:
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.ParseException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.mime.MultipartEntity;
importorg.apache.http.entity.mime.content.FileBody;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.util.EntityUtils;
/**
*
*@author<ahref="mailto:just_szl@hotmail.com">Geray</a>
*@version1.0,2012-6-12
*/
publicclassHttpPostArgumentTest2{
//file1与file2在同一个文件夹下filepath是该文件夹指定的路径
publicvoidSubmitPost(Stringurl,Stringfilename1,Stringfilename2,Stringfilepath){
HttpClienthttpclient=newDefaultHttpClient();
try{
HttpPosthttppost=newHttpPost(url);
FileBodybin=newFileBody(newFile(filepath+File.separator+filename1));
FileBodybin2=newFileBody(newFile(filepath+File.separator+filename2));
StringBodycomment=newStringBody(filename1);
MultipartEntityreqEntity=newMultipartEntity();
reqEntity.addPart("file1",bin);//file1为请求后台的Fileupload;属性
reqEntity.addPart("file2",bin2);//file2为请求后台的Fileupload;属性
reqEntity.addPart("filename1",comment);//filename1为请求后台的普通参数;属性
httppost.setEntity(reqEntity);
HttpResponseresponse=httpclient.execute(httppost);
intstatusCode=response.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK){
System.out.println("服务器正常响应.....");
HttpEntityresEntity=response.getEntity();
System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
System.out.println(resEntity.getContent());
EntityUtils.consume(resEntity);
}
}catch(ParseExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
try{
httpclient.getConnectionManager().shutdown();
}catch(Exceptionignore){
}
}
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
HttpPostArgumentTest2httpPostArgumentTest2=newHttpPostArgumentTest2();
httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveData.do",
"test.xml","test.zip","D://test");
}
}
服务端代码:
publicvoidreceiveData(HttpServletRequestrequest,HttpServletResponseresponse)throwsAppException{
PrintWriterout=null;
response.setContentType("text/html;charset=UTF-8");
Mapmap=newHashMap();
FileItemFactoryfactory=newDiskFileItemFactory();
ServletFileUploadupload=newServletFileUpload(factory);
Filedirectory=null;
List<FileItem>items=newArrayList();
try{
items=upload.parseRequest(request);
//得到所有的文件
Iterator<FileItem>it=items.iterator();
while(it.hasNext()){
FileItemfItem=(FileItem)it.next();
StringfName="";
ObjectfValue=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);
Stringname=fItem.getName();
if(name!=null&&!("".equals(name))){
name=name.substring(name.lastIndexOf(File.separator)+1);
//Stringstamp=StringUtils.getFormattedCurrDateNumberString();
Stringtimestamp_Str=TimeUtils.getCurrYearYYYY();
directory=newFile("d://test");
directory.mkdirs();
StringfilePath=("d://test")+timestamp_Str+File.separator+name;
map.put(fName+"FilePath",filePath);
InputStreamis=fItem.getInputStream();
FileOutputStreamfos=newFileOutputStream(filePath);
byte[]buffer=newbyte[1024];
while(is.read(buffer)>0){
fos.write(buffer,0,buffer.length);
}
fos.flush();
fos.close();
map.put(fName+"FileName",name);
}
}
}
}catch(Exceptione){
System.out.println("读取http请求属性值出错!");
//e.printStackTrace();
logger.error("读取http请求属性值出错");
}
//数据处理
try{
out=response.getWriter();
out.print("{success:true,msg:'接收成功'}");
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
以上所述是小编给大家介绍的HttpClient通过Post上传文件的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!