Get、Post请求之向指定URI发送Get,Post请求

5 篇文章 0 订阅
5 篇文章 0 订阅

一 介绍

1.通过使用PoolingHttpClientConnectionManager类来创建连接池管理器对象,用来设置HttpClient池中的数量,而不是每次使用都去重新创建一个HttpClient对象,以为这样会浪费资源。在发起请求前通过HttpClients的custom()方法来创建一个HttpClientBuilder对象,再通过HttpClientBuilder对象的setConnectionManager(PoolingHttpClientConnectionManager phccm)方法来完成连接池管理对象的设置。
2.在发起请求前我们可以通过RequestConfig类来设置请求的连接超时时间和Socket超时时间。
3.对于请求参数我们使用List< NameValuePair>用来封装请求参数,NameValuePair是一个接口,当我们向list 里面存放参数时,我们可以使用实现了NameValuePair的BasicNameValuePair来存放参数,在参数list创建完成之后使用UrlEncodedFormEntity表单对象类来封装参数,继而发出请求。

代码

pom依赖

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
      <!--<scope>test</scope>-->
    </dependency>
    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.11.3</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

请求代码

public static void main(String[] args) {
		//创建HttpClient连接池管理器
		PoolingHttpClientConnectionManager httpClientConnectionManager=new PoolingHttpClientConnectionManager();
		//设置最大连接数-->连接池中HttpClient对象的个数
		httpClientConnectionManager.setMaxTotal(200);
		//设置目的主机的最大连接数-->多个目的主机时,一个目的主机使用的HttpClient最大个数
		httpClientConnectionManager.setDefaultMaxPerRoute(5);
		//发起请求
		doGet(httpClientConnectionManager);
	}
	public static void  doGet(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager){
		//从连接池中获取HttpClient对象
		CloseableHttpClient httpClient= HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
		//配置请求信息
		RequestConfig requestConfig=RequestConfig.custom().setConnectionRequestTimeout(5*1000).setSocketTimeout(10*1000).build();
		//发起请求
		HttpGet httpGet=new HttpGet("http://www.baidu.com");
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse httpResponse=null;
		try {
			 httpResponse=httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode()==200){
				String content= EntityUtils.toString(httpResponse.getEntity());
				System.out.println(content);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (httpResponse!=null){
				try {
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void  doPost(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager)throws UnsupportedEncodingException{
		//从连接池中获取HttpClient对象
		CloseableHttpClient httpClient= HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
		//配置请求信息
		RequestConfig requestConfig=RequestConfig.custom().setConnectionRequestTimeout(5*1000).setSocketTimeout(10*1000).build();
		//发起请求
		HttpPost httpPost=new HttpPost("http://www.baidu.com");
		httpPost.setConfig(requestConfig);
		//声明集合,封装参数
		List<NameValuePair> nameValuePairList=new ArrayList<NameValuePair>();
		nameValuePairList.add(new BasicNameValuePair("key1","value1"));
		nameValuePairList.add(new BasicNameValuePair("key2","value2"));
		//创建表单对象
		UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(nameValuePairList,"utf8");
		//将表单对象添加到Post请求中
		httpPost.setEntity(formEntity);
		CloseableHttpResponse httpResponse=null;
		try {
			httpResponse=httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode()==200){
				String result= EntityUtils.toString(httpResponse.getEntity());
				System.out.println(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (httpResponse!=null){
				try {
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收响应。它提供了一系列的方法来发送 GET 和 POST 请求,并设置请求头。 以下是使用 HttpClient 发送 GET 请求的示例代码: ```java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); try { URI uri = new URI("http://example.com/api"); HttpGet getRequest = new HttpGet(uri); // 设置请求头 getRequest.addHeader("User-Agent", "Mozilla/5.0"); HttpResponse response = httpClient.execute(getRequest); // 处理响应 System.out.println(response.getStatusLine().getStatusCode()); // 其他处理逻辑... } catch (URISyntaxException | IOException e) { e.printStackTrace(); } } } ``` 以上示例中,我们创建了一个 HttpClient 对象,并使用 `HttpGet` 请求发送 GET 请求。然后,我们通过 `addHeader` 方法设置了请求头中的 User-Agent 字段,模拟了一个浏览器的 User-Agent。最后,使用 `httpClient.execute(getRequest)` 方法发送请求并获取响应。 以下是使用 HttpClient 发送 POST 请求的示例代码: ```java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); try { URI uri = new URI("http://example.com/api"); HttpPost postRequest = new HttpPost(uri); // 设置请求postRequest.addHeader("Content-Type", "application/json"); // 设置请求体 StringEntity requestBody = new StringEntity("{\"key\":\"value\"}"); postRequest.setEntity(requestBody); HttpResponse response = httpClient.execute(postRequest); // 处理响应 System.out.println(response.getStatusLine().getStatusCode()); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity); System.out.println(responseString); // 其他处理逻辑... } catch (URISyntaxException | IOException e) { e.printStackTrace(); } } } ``` 以上示例中,我们使用 `HttpPost` 请求发送 POST 请求。同样,我们通过 `addHeader` 方法设置了请求头中的 Content-Type 字段为 application/json。然后,我们设置了请求体为一个 JSON 字符串。最后,使用 `httpClient.execute(postRequest)` 方法发送请求并获取响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值