本文主要是介绍HttpClient4 post上传文件, struts2 action接收,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
之前写了一个Struts2文件上传的Action,可以编写一个jsp上传页面来测试这个Action,我们也可以编写一个简单的客户端来测试上传的Action。利用HttpClient能够方便的实现这个效果,具体代码如下:
TestUpload.java
package com.figo.test;import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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;public class TestUpload {public static void main(String[] args) {// TODO Auto-generated method stubHttpClient httpclient = new DefaultHttpClient();try {HttpPost httppost = new HttpPost("http://localhost:8080/Upload/fileUpload!execute");FileBody bin = new FileBody(new File("D:\\Wangyf15\\sign.txt"));MultipartEntity reqEntity = new MultipartEntity();reqEntity.addPart("upload", bin);// upload为请求后台的File upload属性httppost.setEntity(reqEntity);HttpResponse response = httpclient.execute(httppost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity resEntity = response.getEntity();// httpclient自带的工具类读取返回数据System.out.println(EntityUtils.toString(resEntity));EntityUtils.consume(resEntity);}} catch (Exception e) {e.printStackTrace();} finally {try {httpclient.getConnectionManager().shutdown();} catch (Exception ignore) {}}}
}
这样比人工构造http post简单很多,HttpClient还有很多强大的能够,有待于继续深入研究。
这篇关于HttpClient4 post上传文件, struts2 action接收的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!