使用CloseableHttpClient 发送post或get请求示例

使用CloseableHttpClient 发送post或get请求示例

今天的工作安排中有一个需求是让我调用另一个系统的接口,把我们系统产生的消息推送上去。这里我是用了CloseableHttpClient向第三方系统发送一个post请求。

通过自己的实践和查阅资料总结了使用CloseableHttpClient的步骤:
(1) 创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3) 如果需要发送请求参数,可调用HttpGet同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4) 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5) 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。

在这里做一个具体实例模拟一下工作中写的代码:
相关jar包maven依赖如下:

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

java代码:

package com.dyz;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Hello world!
 *
 */
public class App 
{
	public static void main( String[] args )
	{
		sendPost("https://www.baidu.com/");
	}

	public static void sendPost(String url){
		// 创建httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300 * 1000)
				.setConnectTimeout(300 * 1000).build();
		// 创建post方式请求对象
		HttpPost post = new HttpPost(url);
		post.setConfig(requestConfig);
		// 请求的数据包为raw,设置报文头为Content-Type
		post.setHeader("Content-Type", "application/json;charset=utf-8");
		
		Map<String, Object> paramTaskUpdate = new HashMap<String, Object>();
		paramTaskUpdate.put("project_id", 1);
		paramTaskUpdate.put("label_id", 2);
		paramTaskUpdate.put("msg_content", 2);
		
		// 装载参数
		StringEntity postingString = new StringEntity(paramTaskUpdate.toString(), "utf-8");
		post.setEntity(postingString);
		// 执行请求并拿到结果
		HttpResponse response = null;
		String content = null;
		try {
			response = httpClient.execute(post);
			// 判断返回状态是否正常
			int state = response.getStatusLine().getStatusCode();
			if (state != HttpStatus.SC_OK) {
				System.out.println("connection faild 错误代码:"+state);
			}

			// 获取结果实体并返回结果
			HttpEntity entity = response.getEntity();
			content = EntityUtils.toString(entity);
			System.out.println(content);
			httpClient.close();			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

查看运行结果:
在这里插入图片描述
注意:
如果是发送get请求,把HttpPost换成HttpGet就行
参考:https://blog.csdn.net/q394895302/article/details/90256482

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,以下是使用HttpClient5发送POSTGET请求Java代码示例: ```java import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException; import java.net.URI; public class HttpClientUtils { /** * 发送GET请求 * * @param url 请求的URL * @return 响应字符串 * @throws IOException */ public static String sendGetRequest(String url) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(url); ClassicHttpResponse response = httpClient.execute(httpGet); return response.getEntity().toString(); } } /** * 发送POST请求 * * @param url 请求的URL * @param params 请求参数(JSON格式) * @return 响应字符串 * @throws IOException */ public static String sendPostRequest(String url, String params) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(URI.create(url)); StringEntity requestEntity = new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); ClassicHttpResponse response = httpClient.execute(httpPost); return response.getEntity().toString(); } } } ``` 这里我们使用了Apache HttpClient5库来发送请求,通过封装成方法,可以方便地在其他地方调用。注意,在使用CloseableHttpClient后,一定要关闭它,否则可能会导致连接泄露和资源浪费。在上面的示例中,我们使用了try-with-resources语法糖来自动关闭CloseableHttpClient
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值