版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ljk126wy/article/details/84136027
Post操作相对于Get操作变化并不是很大,我们只是需要将原来的HttpGet改成HttpPost。不了解获取提交操作的可以参看我的另一篇博客HttpClient4.x之获取请求示例 。但是如果需要进行表单提交,我们需要构造从表单相关操作。这里httpClinet通过NameValuePair维护表单中的每个参数,然后将其传入UrlEncodedFormEntity构造来创建
表单实体。然后在将来自表单实体设置到httpPost中即可。
package cn.zhuoqianmingyue.postoperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class SimplePostHttpClientDemo {
private static Log log = LogFactory.getLog(SimplePostHttpClientDemo.class );
/**
* httpClient post 有参数请求
* @throws IOException
*
*/
@Test
public void doPostWithParam() throws IOException{
//创建HttpClinet
CloseableHttpClient httpClient = HttpClients.createDefault();
//添加HTTP POST请求 这里必须加上http:
HttpPost httpPost = new HttpPost("http://localhost:8080/sbe/mvcUser/");
//设置post参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
//定义请求的参数 设置post参数
parameters.add(new BasicNameValuePair("name", "lijunkui"));
parameters.add(new BasicNameValuePair("age", "18"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,Consts.UTF_8);
//UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info(content);
//释放获取内容 输入流的资源
EntityUtils.consume(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();
}
}
}
项目地址:https://github.com/zhuoqianmingyue/httpclientexamples
其中接口调用项目地址:https://github.com/zhuoqianmingyue/springbootexamples (lesson2_restful_api 分支)