1. 程式人生 > >HttpClient4.x之Post請求示例

HttpClient4.x之Post請求示例

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  分支)