导入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;
}
}

HttpClient测试的更多相关文章

  1. HttpClient 测试web API上传文件实例

    1.使用HttpClient 测试上传文件并且设置header信息: using Lemon.Common; using Newtonsoft.Json; using System; using Sy ...

  2. HttpClient测试框架

    HttpClient是模拟Http协议客户端请求的一种技术,可以发送Get/Post等请求. 所以在学习HttpClient测试框架之前,先来看一下Http协议请求,主要看请求头信息. 如何查看HTT ...

  3. 利用HttpClient测试

    import java.io.IOException;import java.security.cert.CertificateException;import java.security.cert. ...

  4. 使用HttpClient测试SpringMVC的接口

    转载:http://blog.csdn.net/tmaskboy/article/details/52355591 最近在写SSM创建的Web项目,写到一个对外接口时需要做测试,接受json格式的数据 ...

  5. HttpClient测试类请求端和服务端即可能出现乱码的解决

    junit HttpClient 请求端 代码: package com.taotao.httpclient; import java.util.ArrayList; import java.util ...

  6. 使用HttpClient工具类测试WebService接口(soap)

    import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import jav ...

  7. 使用Postman测试https接口时的小问题记录

    测试本地的WebApi接口时,接口是https,自己写的用httpclient测试是可以的, 用postman一直连接不了.原因正是由于https,不过postman在界面上已经给出了可能的原因和解决 ...

  8. 使用HttpClient配置代理服务器模拟浏览器发送请求调用接口测试

    在调用公司的某个接口时,直接通过浏览器配置代理服务器可以请求到如下数据: 请求url地址:http://wwwnei.xuebusi.com/rd-interface/getsales.jsp?cid ...

  9. $Java HttpClient库的使用

    (一)简介 HttpClient是Apache的一个开源库,相比于JDK自带的URLConnection等,使用起来更灵活方便. 使用方法可以大致分为如下八步曲: 1.创建一个HttpClient对象 ...

随机推荐

  1. 【转载】Oracle sqlplus中最简单的一些命令,设置显示的格式

    登录数据库: 方式(1)当我们刚安装Oracle数据库时,登录账户时可以使用win+r 输入sqlplus,进入sqlplus命令窗口,然后输入用户名和密码,这里输入密码时不会有回显 方式(2)使用w ...

  2. Windows驱动开发-DPC定时器

    DCP是一种使用更加灵活的定时器,可以对任意间隔时间进行定时.DPC定时器的内部使用了一个定时器对象KTIMER,当你设定了定时器之后,从设定开始起经过这个时间之后操作系统会将一个DPC定时器的例程插 ...

  3. Python学习第十一课——装饰器

    #装饰器:本质就是函数,为其他函数附加功能原则:1.不修改被修饰函数的源代码2.不修改被修饰函数的调用方式 装饰器=高阶函数+函数嵌套+闭包 #高阶函数 ''' 高阶函数定义: 1.函数接受的参数是一 ...

  4. 【PAT甲级】1035 Password (20 分)

    题意: 输入一个正整数N(<=1000),接着输入N行数据,每行包括一个ID和一个密码,长度不超过10的字符串,如果有歧义字符就将其修改.输出修改过多少组密码并按输入顺序输出ID和修改后的密码, ...

  5. c#能同时继承接口和类吗

    c#能同时继承接口和类吗?( 要你命3000条12级分类:C#/.NET语言被浏览449次2013.09.10   满意答案 mroyal450 采纳率:54%12级 2013.09.11 C# 类, ...

  6. [NOI 2011]NOI 嘉年华

    Description 题库链接 给你 \(n\) 个区间,让你选出其中一些分为两组,要求两组区间不能有交集,组内可以有交集.让你最大化两组之间区间个数较小的那一组的选取区间个数.以及对于每个区间 \ ...

  7. SRS——打开 stream caster

    按照默认的配置编译启动后,发现 stream caster 不起作用,启动时报如下警告: [-- ::][][] stream caster: off 原因是编译SRS时没有打开StreamCaste ...

  8. 用Hyper-v 在win10下使用Docker-Desktop体验kubernetes

    首先开启Hyper-v ,会自动创建一个交换机. 开启internet共享,自动创建的那个交换机(虚拟的网络适配器)会分配一个默认的IP 192.168.137.1,这个IP你不爽,就用注册表搜索并修 ...

  9. MySQL 之存储引擎与数据类型与数据约束

    一.存储引擎场景 1.InnoDB 用于事务处理应用程序,支持外键和行级锁.如果应用对事物的完整性有比较高的要求,在并发条件下要求数据的一致性,数据操作除了插入和查询之外,还包括很多更新和删除操作,那 ...

  10. UniGUI之提示信息MessageDlg及获得信息Prompt(15)

    UniGui的信息弹出框MessageDlg的原型定义如下: procedure MessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons ...