HttpClient通过Post上传文件的实例代码

 更新时间:2016年08月03日 10:02:35   作者:一叶飘舟  
这篇文章主要介绍了HttpClient通过Post上传文件的实例代码的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下

在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。

但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递XML文件)。在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用Upload来进行操作。

HttpClient4.2 jar下载 :http://download.csdn.net/detail/just_szl/4370574

客户端代码:

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中数据解析的五种方式

    Android中数据解析的五种方式

    今天小编就为大家分享一篇关于Android中数据解析的五种方式,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Android BitmapUtils工具类使用详解

    Android BitmapUtils工具类使用详解

    这篇文章主要为大家详细介绍了Android BitmapUtils工具类的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • Android神兵利器之Image Asset Studio的实现

    Android神兵利器之Image Asset Studio的实现

    这篇文章主要介绍了Android神兵利器之Image Asset Studio的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • 详解Android布局优化

    详解Android布局优化

    本篇文章给大家详细分析了Android布局优化的相关知识点以及注意事项,对此有需要的朋友可以参考学习下。
    2018-03-03
  • Android中TextView自动识别url且实现点击跳转

    Android中TextView自动识别url且实现点击跳转

    这篇文章主要介绍了关于Android中TextView自动识别url且实现点击跳转的相关资料,文中给出了详细的示例代码,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
    2017-03-03
  • Android字符串和十六进制相互转化出现的中文乱码问题

    Android字符串和十六进制相互转化出现的中文乱码问题

    这篇文章主要介绍了Android字符串和十六进制相互转化出现的中文乱码问题的相关资料,需要的朋友可以参考下
    2016-02-02
  • Android多线程+单线程+断点续传+进度条显示下载功能

    Android多线程+单线程+断点续传+进度条显示下载功能

    这篇文章主要介绍了Android多线程+单线程+断点续传+进度条显示下载功能,需要的朋友可以参考下
    2017-06-06
  • Android面向单Activity开发示例解析

    Android面向单Activity开发示例解析

    这篇文章主要为大家介绍了Android面向单Activity开发示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Flutter模仿实现微信底部导航栏流程详解

    Flutter模仿实现微信底部导航栏流程详解

    这篇文章主要介绍了Flutter模仿实现微信底部导航栏流程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-05-05
  • Android编程获取手机屏幕分辨率大小的方法

    Android编程获取手机屏幕分辨率大小的方法

    这篇文章主要介绍了Android编程获取手机屏幕分辨率大小的方法,涉及Android基于getWindowManager()方法获取手机屏幕相关信息的使用技巧,需要的朋友可以参考下
    2016-02-02

最新评论