【发布时间】:2019-07-31 02:53:44
【问题描述】:
我正在从 Java 访问一个微服务,它会导致 404-Not found 响应,而通过 Swagger-ui 可以正常工作。
我正在使用 appache HTTPClient。
我有微服务,一个简单的 Spring 控制器,通过 ftp 发送文件。接受包含主机、用户密码等字段的 json 对象... 当我用 swagger-ui 测试它时,它工作正常。 但是,我需要能够以编程方式并从 java concole 应用程序中使用它。 以下是我的代码
控制器代码
@RequestMapping(value = "/SendFiles", method = RequestMethod.POST, consumes
="application/json", produces = "application/json")
public ResponseEntity sendFiles(@RequestBody FTPObject obj) throws
UnknownHostException {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(obj.getFtpUser(), obj.getFtpHost(),
Integer.parseInt(obj.getFtpPort()) );
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(obj.getFtpPassword());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(obj.getRemoteDirectory() );
for(FTPFileObject file: obj.getFiles() ) {
sftpChannel.put("C:\\Developer\\projects\\test-
src\\fileSrc\\testUploadSFtpFile_"+i+".txt",
"testUpload_"+i+".txt");
sftpChannel.put(file.getPathFrom()+file.getFromFileName(),
file.getToFileName());
sftpChannel.exit();
session.disconnect();
return new ResponseEntity("Successfully transmitted list of files",
HttpStatus.OK);
}
catch (JSchException e) {
e.printStackTrace();
return new ResponseEntity("Failed to transmit list of files - >
"+e.getMessage(), HttpStatus.EXPECTATION_FAILED);
}
catch (SftpException e) {
e.printStackTrace();
return new ResponseEntity("Failed to transmit list of files - >
"+e.getMessage(), HttpStatus.EXPECTATION_FAILED);
}
}
这是一个测试的片段
String jsonStr = mapper.writeValueAsString(object);
System.out.println(jsonStr); //This is output I use in swagger-ui
HttpClient httpClient = HttpClientBuilder.create().build(); //Use
// this instead
String postUrl = "http://localhost:8080/WinAPI/sendFiles" ;
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity( jsonStr );
post.setEntity(postingString);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
System.out.println(response.getStatusLine() );
当我运行它并使用 swagger-ui 时,我将文件传输到 ftp。但是当我运行一个测试 java 类(第二个代码段)时,没有异常或错误,但我得到了 404 响应。
请帮忙。可能是什么问题?
【问题讨论】:
-
/WinAPI/sendFiles, WinApi 被定义为你的上下文? sendFiles,我希望 SendFiles ... -
是的!谢谢 !!就是这样,也将produces =“application/json”更改为produces =“text/plain”
标签: java microservices