HttpClient post请求调取接口 例子

package com.xiaojukeji.service;

import java.io.IOException;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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;

import com.google.common.collect.Lists;
import com.xiaojukeji.BaseTest;

public class InviteReservationServiceTest extends BaseTest {
	
	@Test
	public void postUrl () {
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	CloseableHttpResponse response = null;
    	String result = "";
    	try {
			// 封装请求参数  
            List<NameValuePair> paramsList = Lists.newArrayList();  
            paramsList.add(new BasicNameValuePair("nameZh", "3"));
            paramsList.add(new BasicNameValuePair("level", "1"));
            // 转换为键值对  
            String params = EntityUtils.toString(new UrlEncodedFormEntity(paramsList, Consts.UTF_8));
            // 请求地址
    		String uri = "http://10.95.136.132/api/ecmtest/area/add";
            uri += "?" + params;
	        // 创建httpPost.  
            HttpPost httpPost = new HttpPost(uri);  
	        // 通过请求对象获取响应对象
	        response = httpclient.execute(httpPost);
	        // 判断网络连接状态码是否正常(0--200都数正常)
	        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	           result= EntityUtils.toString(response.getEntity(), "utf-8");
	        } 
	        System.out.println(result);
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (response != null) {
    				response.close();
    			}
				httpclient.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			}  
    	}
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_23167527/article/details/78850554