欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java模拟发送form-data的请求方式

程序员文章站 2023-02-17 16:09:06
我就废话不多说了,大家还是直接看代码吧!package com.silot.test; import org.apache.http.httpresponse;import org.apache.ht...

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

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<string, string> 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<string, file> 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<string, string> headerparam;
	/**
	 * 常规参数
	 */
	private map<string, string> bodyparam;
	/**
	 * 待上传的文件参数 filename和file
	 */
	private map<string, file> 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<string, string> getheaderparam() {
//		return headerparam;
//	}
//
//	public void setheaderparam(map<string, string> headerparam) {
//		this.headerparam = headerparam;
//	}

	public map<string, string> getbodyparam() {
		return bodyparam;
	}

	public void setbodyparam(map<string, string> bodyparam) {
		this.bodyparam = bodyparam;
	}

	public map<string, file> getfileparam() {
		return fileparam;
	}

	public void setfileparam(map<string, file> fileparam) {
		this.fileparam = fileparam;
	}
}

以上这篇java模拟发送form-data的请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。