java如何模拟发送form-data的请求

这篇文章主要讲解了java如何模拟发送form-data的请求,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

创新互联建站主要从事成都网站设计、成都网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务大柴旦,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

我就废话不多说了,大家还是直接看代码吧!

package com.silot.test;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
 
public class TestCli
{
  public static void main(String args[]) throws Exception
  {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "------------------------------0ea3fcae38ff", Charset.defaultCharset());
    multipartEntity.addPart("skey", new StringBody("哈哈哈哈哈", Charset.forName("UTF-8")));
    multipartEntity.addPart("operator", new StringBody("啦啦啦啦", Charset.forName("UTF-8")));
    multipartEntity.addPart("VrfKey", new StringBody("渣渣渣", Charset.forName("UTF-8")));
    multipartEntity.addPart("StatCode", new StringBody("00", Charset.forName("UTF-8")));
    multipartEntity.addPart("mass_id", new StringBody("1234", Charset.forName("UTF-8")));
    multipartEntity.addPart("reference_id", new StringBody("21231544", Charset.forName("UTF-8")));
 
    HttpPost request = new HttpPost("http://xiefei.s1.natapp.cc/v1/withdrawCallback");
    request.setEntity(multipartEntity);
    request.addHeader("Content-Type", "Content-Disposition: form-data; boundary=------------------------------0ea3fcae38ff");
 
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
 
    InputStream is = response.getEntity().getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while ((line = in.readLine()) != null)
    {
      buffer.append(line);
    }
 
    System.out.println("发送消息收到的返回:" + buffer.toString());
  }
}

补充知识:java模拟复杂表单post请求

java模拟复杂表单post请求

能支持文件上传

/**
	 * 支持复杂表单,比如文件上传
	 * @param formParam
	 * @return
	 * @throws Exception
	 */
	public static String postWithForm(FormParam formParam) throws Exception {
		String url = formParam.getUrl();
		String charset = "UTF-8";
		String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
		String CRLF = "\r\n"; // Line separator required by multipart/form-data.

		URLConnection connection = new URL(url).openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		try (
				OutputStream output = connection.getOutputStream();
				PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
			) {
			// make body param
			Map bodyParam = formParam.getBodyParam();
			if (null != bodyParam) {
				for (String p : bodyParam.keySet()) {
					writer.append("--" + boundary).append(CRLF);
					writer.append("Content-Disposition: form-data; name=\"" + p + "\"").append(CRLF);
					writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
					writer.append(CRLF).append(bodyParam.get(p)).append(CRLF).flush();
				}
			}
			// Send file.
			Map fileParam = formParam.getFileParam();
			if (null != fileParam) {
				for (String fileName : fileParam.keySet()) {
					writer.append("--" + boundary).append(CRLF);
					writer.append("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\""
							+ fileParam.get(fileName).getName() + "\"").append(CRLF);
					writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(CRLF);
					writer.append("Content-Transfer-Encoding: binary").append(CRLF);
					writer.append(CRLF).flush();
					Files.copy(fileParam.get(fileName).toPath(), output);
					output.flush(); // Important before continuing with writer!
					writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
				}
			}
			// End of multipart/form-data.
			writer.append("--" + boundary + "--").append(CRLF).flush();
		}
		HttpURLConnection conn = (HttpURLConnection) connection;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		int len;
		byte[] buffer = new byte[1024];
		while ((len = conn.getInputStream().read(buffer)) != -1) {
			bout.write(buffer, 0, len);
		}
		String result = new String(bout.toByteArray(), "utf-8");
		return result;
	}

FormParam封装类:

package net.riking.core.utils;

import java.io.File;
import java.util.Map;

public class FormParam {
	private String url;
//	private String auth;
//	/**
//	 * http请求头里的参数
//	 */
//	private Map headerParam;
	/**
	 * 常规参数
	 */
	private Map bodyParam;
	/**
	 * 待上传的文件参数 filename和file
	 */
	private Map fileParam;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

//	public String getAuth() {
//		return auth;
//	}
//
//	public void setAuth(String auth) {
//		this.auth = auth;
//	}
//
//	public Map getHeaderParam() {
//		return headerParam;
//	}
//
//	public void setHeaderParam(Map headerParam) {
//		this.headerParam = headerParam;
//	}

	public Map getBodyParam() {
		return bodyParam;
	}

	public void setBodyParam(Map bodyParam) {
		this.bodyParam = bodyParam;
	}

	public Map getFileParam() {
		return fileParam;
	}

	public void setFileParam(Map fileParam) {
		this.fileParam = fileParam;
	}
}

看完上述内容,是不是对java如何模拟发送form-data的请求有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。


当前标题:java如何模拟发送form-data的请求
当前链接:http://pwwzsj.com/article/gsgcgc.html