HttpClient发送请求,get和post两种方式,分别带参数和不带参数

(一)、导入HttpCLient的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>
  </dependencies>

(二)代码实现

1、httpCLient发送get请求(带参数直接在ulr后跟参数即可)

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

2、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 basicNameValuePair = new BasicNameValuePair("username", "zhangsan");
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password", "123456");
		list.add(basicNameValuePair);
		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();
	}

猜你喜欢

转载自blog.csdn.net/qicui2835/article/details/80945749