2011-09-10 57 views
12

我真的使用使用JSoup下面的代碼提交值:如何使用JSoup發佈文件?

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

,現在我想提交一份文件,太。就像一個帶有文件字段的表單一樣。 這可能嗎?如果是比如何?

回答

14

這是僅支持自Jsoup 1.8.2(2015年4月13日) 通過新的data(String, String, InputStream)方法。

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請求不被支持。最好的辦法是使用一個完整的HTTP客戶端,例如Apache HttpComponents Client。您最終可以將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); 
// ... 
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)該Cookie,然後使用它的文件的後續上傳。

希望它可以幫助傢伙。