“本博标明原创的代码,均不声明任何权责,读者可任意使用和修改,但不负责代码的有效及安全。标明引用的代码,请慎重使用,其权责属于原始作者。谢谢!”
by:不停息的脚步
采用java模拟HTTP提交表单到服务器,(不支持HTTPS),通过POST方式,可以根据需要自定义表单内容及顺序,详细使用方法可以参考main()函数。
第一部分:post表单模拟器
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 模拟HTTP方式的表单提交,包括文件上传<p>
* 使用说明:<p>
* FormsPostSimulator formsPoster = new FormsPostSimulator();<p>
* formsPoster.startPostForms2Server("http://192.168.1.100");<p>
* formsPoster.writeFileForm2Server("name1", "application/zip","E:\\test1.zip");<p>
* formsPoster.writeTextForm2Server("name2", "value");<p>
* formsPoster.writeFileForm2Server("name3", "text/plain","E:\\test2.jpg");<p>
* System.out.println(formsPoster.endPost());<p>
*
* @author 不停息的脚步
* @since 2012-12-29
*
*/
public class FormsPostSimulator {
private String boundary;
private String formsBoundary;
private String endPostBoundary;
private String keyValueBoundary;
private String confirmBoundary;
private URL url;
private HttpURLConnection conn;
private OutputStream oStream;
private InputStream iStream;
private ByteArrayOutputStream byteArrayOStream;
public FormsPostSimulator() throws MalformedURLException {
this.url = new URL("http://localhost");
this.boundary = "------FORM_BOUNDARY_DEFINED_BY_LIANGWEIWEI_20121229";
this.formsBoundary = "\r\n--" + boundary + "\r\n";
this.endPostBoundary = "\r\n--" + boundary + "--\r\n";
this.keyValueBoundary = "\r\n\r\n";
this.confirmBoundary = "\r\n";
}
private void setUrl(String urlString) throws MalformedURLException {
this.url = new URL(urlString);
}
public String getBoundary() {
return this.boundary;
}
public void setBoundary(String boundary) {
this.boundary = boundary;
}
private void openHttpConnection() throws IOException {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + this.boundary);
conn.setRequestProperty("Charsert", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
oStream = conn.getOutputStream();
}
public void writeTextForm2Server(String name, String value)
throws UnsupportedEncodingException, IOException {
StringBuffer sb = new StringBuffer();
sb.append(this.formsBoundary)
.append("Content-Disposition: form-data; name=\"").append(name)
.append("\"").append(this.keyValueBoundary).append(value);
this.oStream.write(sb.toString().getBytes("utf-8"));
}
public void writeFileForm2Server(String name, String fileType,
String filePath) throws UnsupportedEncodingException, IOException {
StringBuffer sb = new StringBuffer();
sb.append(this.formsBoundary)
.append("Content-Disposition: form-data; name=\"")
.append(name)
.append("\"; filename=\"")
.append(filePath.substring(filePath.lastIndexOf(File.separator)))
.append("\"").append(this.confirmBoundary)
.append("Content-Type: ").append(fileType)
.append(this.keyValueBoundary);
this.oStream.write(sb.toString().getBytes("utf-8"));
File file = new File(filePath);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024 * 5];
while ((bytes = in.read(bufferOut)) != -1) {
this.oStream.write(bufferOut, 0, bytes);
}
in.close();
}
private void writeEndBoundery2Server() throws UnsupportedEncodingException,
IOException {
this.oStream.write(this.endPostBoundary.getBytes("utf-8"));
}
private String getResponse() throws IOException {
iStream = conn.getInputStream();
int aChar;
this.byteArrayOStream = new ByteArrayOutputStream();
while ((aChar = this.iStream.read()) != -1) {
this.byteArrayOStream.write(aChar);
}
return new String(this.byteArrayOStream.toByteArray());
}
private void closeOutputStream() throws IOException {
this.oStream.close();
}
private void closeInputStream() throws IOException {
this.iStream.close();
}
private void closeHttpConnection() throws IOException {
closeInputStream();
closeOutputStream();
this.conn.disconnect();
}
public void startPostForms2Server(String urlString) throws IOException {
setUrl(urlString);
openHttpConnection();
}
public String endPost() throws IOException {
writeEndBoundery2Server();
String response = getResponse();
closeHttpConnection();
return response;
}
/**
* @test
*/
public static void main(String[] args) {
try {
FormsPostSimulator formsPoster = new FormsPostSimulator();
formsPoster
.startPostForms2Server("http://192.168.1.100/upload/upAll.php");
formsPoster.writeFileForm2Server("upload[]", "application/zip",
"E:\\liangvv\\httpdocs\\filesystem\\test1.theme");
formsPoster.writeFileForm2Server("upload[]", "text/plain",
"E:\\liangvv\\httpdocs\\filesystem\\test2.jpg");
formsPoster.writeTextForm2Server("fileName", "hello");
System.out.println(formsPoster.endPost());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
第二部分:测试用服务器PHP代码(均来源于《大道php》)
uploadAll.php<form enctype="multipart/form-data" action="upAll.php" method="POST">
<input name="upload[]" type="file"><br>
<input name="upload[]" type="file"><br>
<input name="upload[]" type="file"><br>
<input type="submit" value="上传">
</form>
upAll.php
<?php
echo "upload start...<br>";
foreach($_FILES['upload']['name'] as $index=>$name) {
echo $name."upload start...<br>";
$uploadfile="upload/".$name;
if(move_uploaded_file($_FILES['upload']['tmp_name'][$index], $uploadfile)) {
echo $name."upload ok...<br>";
} else {
echo $name."upload false...<br>";
}
}
?>