httpclient 3.1 上传文件 同时传递参数
2011-04-13 01:21:40| 分类:
java
| 标签:
|举报
|字号大中小 订阅
直接贴出代码:
package tools;
import java.io.File;
import java.io.IOException;
import javax.xml.rpc.holders.StringHolder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
public class UploadHelper {
public static int post(String url,File[] files,NameValue[] nvs,StringHolder response) throws IOException{
int status = 0;
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
Part[] parts = new Part[files.length+nvs.length];
int index = 0;
for(File file:files){
parts[index++]=new FilePart(file.getName(), file);
}
for(NameValue nv:nvs){
parts[index++]=new StringPart(nv.name, nv.value);
}
MultipartRequestEntity entry = new MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(entry);
try {
status = client.executeMethod(method);
response.value=new String(method.getResponseBody(),method.getResponseCharSet());
} catch (HttpException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally{
method.releaseConnection();
}
return status;
}
}
class NameValue{
public String name;
public String value;
}
评论这张
转发至微博
转发至微博
评论