HttpClient发送请求:get和post

第一步:jar包

  <dependencies>
	  	<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.6</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
  </dependencies>

第一种:HttpClient发送GET请求

	public void HttpClientGet() throws Exception {
		// 获取http客户端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通过HttpGet方式来实现我们的get请求
		HttpGet httpGet = new HttpGet("http://192.168.100.10:8080/project/login?username=zhangsan&password=123");
		// 通过client调用execute方法,得到我们的执行结果就是一个response,所有的数据都封装在response里面了
		CloseableHttpResponse httpResponse = client.execute(httpGet);
		// HttpEntity
		// 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
		// 所有的响应的数据,也全部都是封装在HttpEntity里面
		HttpEntity entity = httpResponse.getEntity();
		// 通过EntityUtils 来将我们的数据转换成字符串
		String str = EntityUtils.toString(entity, "UTF-8");
		// EntityUtils.toString(entity)
		System.out.println(str);
		// 关闭
		Response.close();
	}

第一种:HttpClient发送POST请求

	public void HttpClientPost() throws Exception {
		// 获取默认的请求客户端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通过HttpPost来发送post请求
		HttpPost httpPost = new HttpPost("http://www.itcast.cn");
		/*
		 * post带参数开始
		 */
		// 第三步:构造list集合,往里面丢数据
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair1 = new BasicNameValuePair("username", "zhangsan");
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password", "123");
		list.add(basicNameValuePair1);
		list.add(basicNameValuePair2);
		// 第二步:我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		// 第一步:通过setEntity 将我们的entity对象传递过去
		httpPost.setEntity(formEntity);
		/*
		 * post带参数结束
		 */
		// HttpEntity
		// 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
		// 通过client来执行请求,获取一个响应结果
		CloseableHttpResponse response = client.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String str = EntityUtils.toString(entity, "UTF-8");
		System.out.println(str);
		// 关闭
		response.close();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值