写一个httpclient接口上传文件的java代码
时间: 2023-06-02 19:06:47 浏览: 271
好的,这是一个简单的Httpclient上传文件的Java代码:
```
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.File;
public class HttpclientUpload {
public static void main(String[] args) {
// 提交的文件路径
String filePath = "C:\\Users\\User\\Desktop\\test.txt";
// 上传的地址
String uploadUrl = "http://localhost:8080/UploadFileServlet";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(uploadUrl);
FileBody fileBody = new FileBody(new File(filePath));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", fileBody)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
```
这个代码使用了Apache Httpclient库来完成文件上传,需要注意的是文件上传的地址需要根据实际情况修改。如果您有任何问题,可以随时问我。
阅读全文