JAVA_模拟HTTP表单POST文本或文件

“本博标明原创的代码,均不声明任何权责,读者可任意使用和修改,但不负责代码的有效及安全。标明引用的代码,请慎重使用,其权责属于原始作者。谢谢!”

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>";
  }
}
?>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,我们可以使用HttpURLConnection或HttpClient来模拟提交。 1. 使用HttpURLConnection: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStreamWriter; public class FormSubmitter { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/form.php"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法 conn.setRequestMethod("POST"); // 设置请求头 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 允许写入数据 conn.setDoOutput(true); // 创建输出流 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); // 写入数据 out.write("name=value&name2=value2"); // 关闭输出流 out.close(); // 获取响应码 int responseCode = conn.getResponseCode(); // 关闭连接 conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用HttpClient: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.entity.StringEntity; public class FormSubmitter { public static void main(String[] args) { try { // 创建HttpClient对象 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost对象 HttpPost httpPost = new HttpPost("http://example.com/form.php"); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/5.0"); // 创建请求体 StringEntity requestEntity = new StringEntity("name=value&name2=value2"); httpPost.setEntity(requestEntity); // 发送请求 httpClient.execute(httpPost); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上是两种常用的Java模拟提交的方式,根据实际需求选择适合自己的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值