How can i programmatically upload a file to a website?

后端 未结 5 1388
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 12:10

I have to upload a file to a server which only exposes a jsf web page with file upload button (over http). I have to automate a process (done as java stand alone process) wh

5条回答
  •  情歌与酒
    2020-11-28 12:58

    What you'll need to do is to examine the HTML on the page and work out what parameters are needed to post the form. It'll probably look something like this:

    Based on that you can write some code to do a POST request to the url:

    String data = URLEncoder.encode("value1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("file1", "UTF-8") + "=" + URLEncoder.encode(FileData, "UTF-8");
    
    // Send data
    URL url = new URL("http://servername.com/RequestURL");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();
    

    Remember that the person who wrote the page might do some checks to make sure the POST request came from the same site. In that case you might be in trouble, and you might need to set the user agent correctly.

提交回复
热议问题