2011-09-10 11 views
12

I`m:JSoupを使ってファイルを投稿するには? JSoupを使用して、次のコードのポスト値を使用して

Document document = Jsoup.connect("http://www......com/....php") 
        .data("user","user","password","12345","email","[email protected]") 
        .method(Method.POST) 
        .execute() 
        .parse(); 

そして今、私はあまりにも、ファイルを送信したいです。ファイルフィールドを持つフォームと同じです。 これは可能ですか?どうすればいい?

答えて

14

これは、新しいdata(String, String, InputStream)メソッドを使用して1.8.2(Apr15、2015年4月13日) からのみサポートされます。古いバージョンでは

String url = "http://www......com/....php"; 
File file = new File("/path/to/file.ext"); 

Document document = Jsoup.connect(url) 
    .data("user", "user") 
    .data("password", "12345") 
    .data("email", "[email protected]") 
    .data("file", file.getName(), new FileInputStream(file)) 
    .post(); 
// ... 

multipart/form-data要求を送信することはサポートされていません。最も良いのは、Apache HttpComponents Clientのような完全なHTTPクライアントを使用することです。最終的にHTTPクライアントの応答はStringとなり、Jsoup#parse()メソッドにフィードできます。

String url = "http://www......com/....php"; 
File file = new File("/path/to/file.ext"); 

MultipartEntity entity = new MultipartEntity(); 
entity.addPart("user", new StringBody("user")); 
entity.addPart("password", new StringBody("12345")); 
entity.addPart("email", new StringBody("[email protected]")); 
entity.addPart("file", new InputStreamBody(new FileInputStream(file), file.getName())); 

HttpPost post = new HttpPost(url); 
post.setEntity(entity); 

HttpClient client = new DefaultHttpClient(); 
HttpResponse response = client.execute(post); 
String html = EntityUtils.toString(response.getEntity()); 

Document document = Jsoup.parse(html, url); 
// ... 
4

受け入れ答え作品や執筆時点では正確でしたが、それ以来JSoupが進化しsince version 1.8.2 it is possible to send files as part of multipart formsました:

File file1 = new File("/path/to/file"); 
FileInputStream fs1 = new FileInputStream(file1); 

Connection.Response response = Jsoup.connect("http://www......com/....php") 
    .data("user","user","password","12345","email","[email protected]")    
    .data("file1", "filename", fs1) 
    .method(Method.POST) 
    .execute(); 
0

この投稿は、正しい道に私を導いたが、私は微調整しなければなりませんでした私のユースケースの作業をするための回答を掲載しました。

 FileInputStream fs = new FileInputStream(fileToSend); 
     Connection conn = Jsoup.connect(baseUrl + authUrl) 
       .data("username",username) 
       .data("password",password); 
     Document document = conn.post(); 

     System.out.println("Login successfully! Session Cookie: " + conn.response().cookies()); 


     System.out.println("Attempting to upload file..."); 
     document = Jsoup.connect(baseUrl + uploadUrl) 
       .data("file",fileToSend.getName(),fs) 
       .cookies(conn.response().cookies()) 
       .post(); 

基本的な違いは、私が最初に、サイトへのログイン応答(conn)からクッキーを保持し、ファイルのアップロード、後続のためにそれを使用することである:ここに私のコードです。

皆さんに役立つことを願っています。

関連する問題