您的位置:首页 > 理论基础 > 计算机网络

RESTEasy使用httpclient上传文件

2014-02-26 10:13 169 查看
我们使用resteasy-multipart的MultipartFormDataInput类来操作数据。

1) 更新maven项目依赖

添加下面的maven依赖到你的项目:
<!-- core library -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.3.1.GA</version>
</dependency>
<dependency>
<groupId>net.sf.scannotation</groupId>
<artifactId>scannotation</artifactId>
<version>1.0.2</version>
</dependency>
<!-- JAXB provider -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>2.3.1.GA</version>
</dependency>
<!-- Multipart support -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>2.3.1.GA</version>
</dependency>
<!-- For better I/O control -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>


同样也添加以下图片中的jar包,到你的项目依赖中:



2) 准备http
client,用于客户端上传文件:

package com.howtodoinjava.client.upload;

import java.io.File;

import org.apache.http.HttpResponse;
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.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class DemoFileUploader
{
public static void main(String args[]) throws Exception
{
DemoFileUploader fileUpload = new DemoFileUploader () ;
File file = new File("C:/Lokesh/Setup/workspace/RESTfulDemoApplication/target/classes/Tulips.jpg") ;
//Upload the file
fileUpload.executeMultiPartRequest("http://localhost:8080/RESTfulDemoApplication/user-management/image-upload",
file, file.getName(), "File Uploaded :: Tulips.jpg") ;
}

public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) throws Exception
{
HttpClient client = new DefaultHttpClient() ;
HttpPost postRequest = new HttpPost (urlString) ;
try
{
//Set various attributes
MultipartEntity multiPartEntity = new MultipartEntity () ;
multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

FileBody fileBody = new FileBody(file, "application/octect-stream") ;
//Prepare payload
multiPartEntity.addPart("attachment", fileBody) ;

//Set to request body
postRequest.setEntity(multiPartEntity) ;

//Send request
HttpResponse response = client.execute(postRequest) ;

//Verify response if any
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch (Exception ex)
{
ex.printStackTrace() ;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RestEasy