HttpClient测试

导入maven依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.1.37</version>
</dependency>

使用httpclient提交get和post请求

package com.ilcbs.test;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
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.HttpGet;
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;

/**
 * 测试HttpClient
 * @author guorong
 *
 */
public class HttpClientTest {
    
    //测试get请求
    @Test
    public void testGet() throws ClientProtocolException, IOException{
        //获取httpClient客户端
        CloseableHttpClient client = HttpClients.createDefault();
        //创建get请求
        HttpGet httpGet = new HttpGet("https://www.baidu.com");
        //执行请求,返回响应
        CloseableHttpResponse response = client.execute(httpGet);
        
        //获取响应实体
        HttpEntity entity = response.getEntity();
        //解析实体内容,可以设置解析字符集
        String content = EntityUtils.toString(entity,"utf-8");
        System.out.println(content);
    }
    
    
    //测试post请求
    @Test
    public void testPost() throws ClientProtocolException, IOException{
        //创建httpclient客户端
        CloseableHttpClient client = HttpClients.createDefault();
        
        //创建post请求
        HttpPost httpPost = new HttpPost("https://passport.baidu.com/v2/api/?login");
        
        ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
        arrayList.add(new BasicNameValuePair("username", "cgx"));
        arrayList.add(new BasicNameValuePair("password", "123456"));
        UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(arrayList);
        
        httpPost.setEntity(urlEntity);
        
        //执行请求
        CloseableHttpResponse response = client.execute(httpPost);
        
        //获取响应实体内容
        HttpEntity entity = response.getEntity();
        //指定编码解析实体内容
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println(content); 
    }
}

 

使用工具类

@Test
public void testHttpUtils(){
    HashMap map = new HashMap();
    map.put("username", "cgx");
    map.put("password", "123456");
    String doPost = HttpClientUtil.doPost("http://localhost:8080/itcast297/loginAction_login",map);
    String zTreeJson = HttpClientUtil.doGet("http://localhost:8080/itcast297/sysadmin/roleAction_genzTreeNodes?id=4028a1c34ec2e5c8014ec2ebf8430001");
    System.out.println(zTreeJson);
}

 

 工具类:

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;

public class HttpClientUtil {

    public  static HttpClientContext context = null;  
     static {  
         System.out.println("====================begin");
         context = HttpClientContext.create();  
     }  
    
//get请求,携带请求参数
public static String doGet(String url, Map<String, String> param) { System.out.println("====================get"); // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet,context); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; }   
   //get请求没有请求参数
public static String doGet(String url) { return doGet(url, null); }   
  
//post请求,携带请求参数
public static String doPost(String url, Map<String, String> param) { System.out.println("====================post"); // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost,context); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; }   
  
   //post请求,没有请求参数
public static String doPost(String url) { return doPost(url, null); }


//Post请求, 携带json字符串
public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } }

 

posted @ 2018-08-26 11:29  Aaron2705  阅读(474)  评论(0编辑  收藏  举报