2017-10-16 69 views
0

我正在尝试登录网页并上传文件。搜索了一段时间后,我发现了一个使用硒的解决方案。在页面的HTML代码如下所示:使用java将文件上传到php网站

<html> 
    <head><title>some title</title></head> 
    <body> 
    <h1>upload</h1> 
     upload your file<br> 
     <form action="hx2.php" method="post" enctype="multipart/form-data"> 
      <input type="hidden" name="action" value="upload"> 
      <input type="hidden" name="debug" value=""> 
      <input type="file" name="filename"> 
      <input type="submit" value="Datei senden"> 
      <input type="reset"> 
     </form> 
     </body> 
</html> 

和用于登录页面,上传我的文件中的Java代码:

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 

public class Example_1 { 
    public static final String BASEURL = "somesite.de/"; 
    private static WebDriver driver; 
    public static void main(String[] args) { 
     String geckoPath = "C:\\...\\gecko\\geckodriver.exe"; 
     System.setProperty("webdriver.gecko.driver",geckoPath); 
     driver = new FirefoxDriver(); 
     loginAndUpload("uname", "pwd","C:\\...\\myFile.xml");   
    } 
    public static void loginAndUpload(String uname, String pwd, String filePath){ 
     String URL = "http://" + uname + ":" + pwd + "@" + BASEURL; 
     driver.get(URL); 

     driver.findElement(By.name("filename")).sendKeys(filePath); 

     driver.findElement(By.cssSelector("input[type=submit]")).click(); 
     driver.findElement(By.name("tan")).sendKeys("123"); 

     driver.findElement(By.cssSelector("input[type=submit]")).click(); 

     System.out.println(driver.getPageSource().contains("successful")?"successfully uploaded":"upload not successful"); 
     driver.quit(); 
    } 
} 

为了使这项工作,我需要下载geckodriver .exe并添加3个外部jar文件。此外,由于我是硒新手,我试着读一些关于它的知识,并发现它是一个软件测试框架。所以我的问题是:这是一个正确的方式来上传文件或我想念硒? 如果是这样,是否有更简单/更简单的方式登录网站并上传文件?

回答

1

您应该给HttpClient一个机会。这是有据可查的,并有很多例子。 HttpClient是在可扩展OO框架中的所有HTTP方法(GET,POST,PUT,DELETE,HEAD,OPTIONS和TRACE)的完整实现。许多认证模式已经实现。