使用Java HttpClient将文件上载到apache web服务器
我正在尝试使用Java HttpClient和本地apache web服务器将文件上载到web服务器。对于apache web服务器,我创建了一个虚拟主机,并将其文件夹的完全权限授予了我的ubuntu用户名(而不是根用户)。 我加了一个标志。png文件位于我的项目文件夹的根目录下,但在我的apache虚拟主机的文件夹中没有记录任何内容
当运行主(也是唯一)java类时,我总是得到这个返回答案,RequestBuilder指向http://localhost:
<html>
<head>
<title>Welcome to test upload!</title>
</head>
<body>
<h1>Success! The test upload virtual host is working!</h1>
</body>
</html>
HTTP/1.1 200 OK
如果我改变主意http://localhost到http://localhost/tester(tester是一个新文件夹),我得到了这个答案,但tester文件夹中没有任何记录:
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://localhost/tester/">here</a>.</p>
<hr>
<address>Apache/2.4.41 (Ubuntu) Server at localhost Port 80</address>
</body></html>
HTTP/1.1 301 Moved Permanently
我基本上复制粘贴了这个tutorial的代码
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
public class MultipartUploadExample {
public static void main(String args[]) throws Exception{
//Creating CloseableHttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating a file object
File file = new File("sample.txt");
//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entitybuilder.build();
//Building the RequestBuilder request object
RequestBuilder reqbuilder = RequestBuilder.post("http://localhost");
//Set the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);
//Printing the status and the contents of the response
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
System.out.println(httpresponse.getStatusLine());
}
}
共 (0) 个答案