模拟以Form表单方式发送Http请求

有的时候我们需要模拟实现以表单的方式提交一个请求,看看后台服务是否正常处理,这里我们简单实现并记录一下,看看怎么实现。

废话不多说,直接贴出代码:

package com.iflytek.ossp.vaserver.cmd;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Test1 {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		Map params = new HashMap();
		params.put("name", "majing");
		String result = httpPostWithForm("http://localhost:8081/simulation/vaclient/ttokenvalidate/success", params);
		System.out.println(result);
	}

	private static String httpPostWithForm(String url, Map params) throws ClientProtocolException, IOException {
		List pairList = new ArrayList();
		for (Entry param : params.entrySet()) {
			pairList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpPost httpPost = new HttpPost(url);
		
		//添加代理,用于抓包
		HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http"); 
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(8000).setConnectTimeout(8000).setSocketTimeout(8000).setProxy(proxy).build();
        httpPost.setConfig(requestConfig);
		
		httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
		String respContent = null;
		HttpClient _httpClient = HttpClients.createDefault();
		HttpResponse resp = _httpClient.execute(httpPost);
		HttpEntity he = resp.getEntity();
		respContent = EntityUtils.toString(he, "UTF-8");
		return respContent;
	}
}

在上面的代码中,为了使用Fiddler抓包查看是否请求报文是以Post方式表单提交方式请求的,所以在代码中增加了相关的代理设置代码。

这里使用的HttpClient包的版本是4.3.2,经过测试用例可以正常执行。这里仅做知识点的记录,有需要的可以看下,没有需要的勿喷,谢谢!

你可能感兴趣的:(JAVA编程)