Java 服务端通信之httpClient

本文介绍如何使用Java的HttpClient库发送POST请求。通过示例代码展示了如何配置请求超时时间、设置请求参数,并解析响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      httpClient是java服务端可以主动发送http请求的很好用的一个轻量级工具。使用起来应该说是非常方便的。

      首先在pom.xml文件中引入依赖:

      <!-- HTTP访问工具httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4.1</version>
        </dependency>

       代码更是简洁:

      

	CloseableHttpResponse response = null;
        // 创建http连接(CloseableHttpClient是从httpclient4.3版本引进的可直接关闭释放连接的class)
	CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个post请求
	HttpPost post = new HttpPost("http://192.168.x.xxx:8080/login/enter.do");
	try {
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间 
		post.setConfig(requestConfig);
		//写入参数,有两种方法,一种是将参数逐个放入list中,另一种是拼接在一起(根据自己的需求任选一种)。
		//第一种
		List<NameValuePair> list = new ArrayList<>();//定义名值对列表
		JSONObject obj = new JSONObject();
		//把参数放到list中  
		list.add(new BasicNameValuePair("userName", "zhangsan"));
                list.add(new BasicNameValuePair("passWord", "666"));
		//把参数编码到表单实体中
		HttpEntity postentity = new UrlEncodedFormEntity(list,"utf-8");
			
		//第二种,拼接参数
		/*String baseString = "userName=zhangsan&passWord=666";
		StringEntity stringEntity = new StringEntity(baseString,"utf-8"); 
		post.setEntity(stringEntity);//将请求实体放到post请求中*/
			
		post.setEntity(postentity);//将请求实体放到post请求中
		post.completed();
		response = httpclient.execute(post);// 用客户端去执行post请求,返回响应
		HttpEntity entity = response.getEntity();// 从响应中拿到响应实体
		//收到的响应
		String responseText = EntityUtils.toString(entity);
	} catch (Exception e){
		e.printStackTrace();
	}finally{
	    if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            if(httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
	}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值