使用Rest API通过HTTP将文件从Java后端上载到远程服务器的问题。
我的文件驻留在我的机器上的某个位置,如C://users//abc.txt,我想编写一个Java程序来使用REST API通过HTTP传输此文件。我用MockHttpServelet请求创建的要求,但不知何故,我无法将文件使用Rest API通过HTTP将文件从Java后端上载到远程服务器的问题。
使用HttpClient转移:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
身份验证:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
String username = "username"; // Replace with your username
String password = "password"; // Replace with your password
RequestConfig requestConfig =
RequestConfig.custom().
setAuthenticationEnable(true).
build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredential(username, password));
CloseableHttpClient httpClient =
HttpClients.custom().
setDefaultRequestConfig(requestConfig).
setDefaultCredentialsProvider(credentialsProvider).
build();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
感谢Greg。任何想法需要指定session/userCredentials,以便服务器可以访问它? –
身份验证使用是另一个问题。 使用HttpClients.custom()。setDefaultRequestConfig(requestConfig).setDefaultCredentialsProvider(credentialsProvider)。 –
它会不会影响性能?我的意思是当文件打开传输时,JVM会将文件加载到内存中。如果它很大,我相信会有性能问题。任何想法如何可以避免? –
String location="C:\\Usersabc.img";
Path path = Paths.get(location);
String name=location.substring(location.lastIndexOf("\\")+1);
MultipartEntity multipart= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
multipart.addPart("image", new ByteArrayBody(Files.readAllBytes(path), ContentType.APPLICATION_OCTET_STREAM.getMimeType(),name));
}
catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
这也适用于我 –
不知道关于REST API,但是我已经使用MySql作为后端上载了服务器上的文件。 –
不知道你使用的是什么,是MongoDB吗? –
Milind,独立Java应用程序正在后端运行。我有一个使用Rest API将文件从我的目录传输到某个服务器的功能。服务器接受Rest API Resquest。我不想使用任何协议如scp来进行文件传输。服务器将只通过Rest API接受请求 –