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

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

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的请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • java模拟post请求发送json的例子

    java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main.utils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtilTest { Log log = new Log(this.getClass());//初始化

  • Java利用HttpClient模拟POST表单操作应用及注意事项

    HttpClient使用post方法提交数据 源代码: 复制代码 代码如下: package post; import Java.io.IOException; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commo

  • java使用httpclient模拟post请求和get请求示例

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.Header;import org

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

    我就废话不多说了,大家还是直接看代码吧! 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.apa

  • java模拟http的Get/Post请求,并设置ip与port代理的方法

    本文涉及3个基本点: 1.因为很多公司的内网都设有代理,浏览器通过ip与port上网,而java代码模拟http get方式同样需要外网代理: 2.Java实现http的Get/Post请求代码: 3.主要是设置HttpURLConnection请求头里面的属性 比如Cookie.User-Agent(浏览器类型)等等. 比如:http请求中添加Header conn.setRequestProperty("Authorization", authorization); 注:我就在网上

  • Postman模拟发送带token的请求方法

    Postman模拟发送带token的请求方法 1)google浏览器中安装扩展程序Interceptor 2)Postman中开启Interceptor即可 以上这篇Postman模拟发送带token的请求方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们. 您可能感兴趣的文章: PostMan post请求发送Json数据的方法 postman测试post请求参数为json类型的实例讲解

  • java模拟多线程http请求代码分享

    java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 实例代码: package test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Exec

  • Java模拟新浪和腾讯自动登录并发送微博

    Java模拟新浪和腾讯自动登录并发送微博功能分享给大家,供大家参考,具体内容如下 1.准备工作 只是登录无需申请新浪和腾迅的开发者账号,如果需要发送微博功能,需要申请一个新浪和腾迅的开发者账号,并添加一个测试应用. 过程请参考官方帮助文档,申请地址:新浪:http://open.weibo.com    腾迅:http://dev.t.qq.com/ 我们需要的是App Key和App Secre及redirect_URI,源代码中已经包含了我申请的测试key,但由于限制直接用我的key你们的账

  • Servlet获取AJAX POST请求中参数以form data和request payload形式传输的方法

    本文实例讲述了Servlet获取AJAX POST请求中参数以form data和request payload形式传输的方法.分享给大家供大家参考,具体如下: HTTP请求中,如果是get请求,那么表单参数以name=value&name1=value1的形式附到url的后面,如果是post请求,那么表单参数是在请求体中,也是以name=value&name1=value1的形式在请求体中.通过chrome的开发者工具可以看到如下(这里是可读的形式,不是真正的HTTP请求协议的请求格式)

  • django实现web接口 python3模拟Post请求方式

    作为抛砖引玉,用python3实现百度云语音解析,首先需要模拟Post请求把音频压缩文件丢给百度解析. 但是遇到一个问题客户端怎麽丢数据都是返回错误,后来在本地用django搭建了一个接口模拟一下,发现还是有地方弄错了! 研究这玩意有啥用? 1.用python做自动化运维,客户端发送收集好的信息(模拟post发送) 2.前后端分离,django只提供数据,前端用vuejs,nodejs实现 3.3端 立体通信 上代码: url.py from django.conf.urls import ur

  • 浅谈Java HttpURLConnection请求方式

    一)URL代理请求 ​ 该方式请求有两种代理方式. 方式一:使用该方式代理之后,之后的所有接口都会使用代理请求 // 对http开启全局代理 System.setProperty("http.proxyHost", "192.168.1.1"); System.setProperty("http.proxyPort", "80"); // 对https开启全局代理 System.setProperty("https.

  • Java 模拟真正的并发请求详情

    java中模拟并发请求,自然是很方便的,只要多开几个线程,发起请求就好了.但是,这种请求,一般会存在启动的先后顺序了,算不得真正的同时并发! 怎么样才能做到真正的同时并发呢? 是本文想说的点,java中提供了闭锁 CountDownLatch, 刚好就用来做这种事就最合适了. 只需要: 开启n个线程,加一个闭锁,开启所有线程: 待所有线程都准备好后,按下开启按钮,就可以真正的发起并发请求了. package com.test; import java.io.BufferedReader; imp

随机推荐