Как загрузить файл по определенному пути Ubuntu, используя HttpClient - PullRequest
0 голосов
/ 19 сентября 2019

Я получаю ошибку 404 при загрузке файла на мой сервер Ubuntu.

public class Test {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        // TODO Auto-generated \ stub

        CloseableHttpClient httpClient = HttpClients.createDefault();
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "password");
        System.out.println(creds.getUserPrincipal().getName());
        System.out.println(creds.getPassword());
        HttpPost uploadFile = new HttpPost("http://10.0.0.45/home");


        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

        // This attaches the file to the POST:
        File f = new File("D:\\chinta\\abc.txt");
        builder.addBinaryBody(
            "file",
            new FileInputStream(f),
            ContentType.APPLICATION_OCTET_STREAM,
            f.getName()
        );

        HttpEntity multipart = builder.build();
        uploadFile.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        System.out.println("=s========================"+response.getStatusLine());

        HttpEntity responseEntity = response.getEntity();
    }

}

Я получаю ошибку 404 в response.getstatus.

Ответы [ 2 ]

0 голосов
/ 20 сентября 2019
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

public class FileUpload {

    static ChannelSftp channelSftp = null;
    static Session session = null;
    static Channel channel = null;
    static String PATHSEPARATOR = "/";

    /**
     * @param args
     */
    public static void main(String[] args) {
        String SFTPHOST = "10.16.70.123"; // SFTP Host Name or SFTP Host IP Address
        int SFTPPORT = 22; // SFTP Port Number
        String SFTPUSER = "mlc-dgate"; // User Name
        String SFTPPASS = "mypassword"; // Password
        String SFTPWORKINGDIR = "/home/mlc-dgate/instances"; // Source Directory on SFTP server
        String LOCALDIRECTORY = "D:\\chinta/abc.txt"; // Local Target Directory

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect(); // Create SFTP Session
            channel = session.openChannel("sftp"); // Open SFTP Channel
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR); // Change Directory on SFTP Server

            recursiveFolderUpload(LOCALDIRECTORY,SFTPWORKINGDIR);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (channelSftp != null)
                channelSftp.disconnect();
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();

        }

    }

    /**
     * This method is called recursively to Upload the local folder content to
     * SFTP server
     * 
     * @param sourcePath
     * @param destinationPath
     * @throws SftpException
     * @throws FileNotFoundException 
     */
    private static void recursiveFolderUpload(String sourcePath, String destinationPath) throws SftpException, FileNotFoundException {

        File sourceFile = new File(sourcePath);
        if (sourceFile.isFile()) {

            // copy if it is a file
            channelSftp.cd(destinationPath);
            if (!sourceFile.getName().startsWith("."))
                channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);

        } else {

            System.out.println("inside else " + sourceFile.getName());
            File[] files = sourceFile.listFiles();

            if (files != null && !sourceFile.getName().startsWith(".")) {

                channelSftp.cd(destinationPath);
                SftpATTRS attrs = null;

                // check if the directory is already existing
                try {
                    attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
                } catch (Exception e) {
                    System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
                }

                // else create a directory
                if (attrs != null) {
                    System.out.println("Directory exists IsDir=" + attrs.isDir());
                } else {
                    System.out.println("Creating dir " + sourceFile.getName());
                    channelSftp.mkdir(sourceFile.getName());
                }

                for (File f: files) {
                    recursiveFolderUpload(f.getAbsolutePath(), destinationPath + "/" + sourceFile.getName());
                }

            }
        }

    }

}
0 голосов
/ 19 сентября 2019

Я попробовал твой код, и он работает нормально.404 обычно означает, что URL-адрес запроса не существует на стороне сервера.Может, тебе стоит это проверить.

...