通过httpClient实现跨服务获取数据

本文介绍了如何在Java中利用httpClient库进行跨服务数据获取。详细步骤包括引入 httpClient 依赖,编写发送GET请求的代码,并展示了响应数据的处理示例。

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

携带参数发送httpClient (get)请求,亲测有效。
第一步引入httpClient依赖
在这里插入图片描述
第二步上代码

@Test
	public void doHttpClientTest(){
		// 获得Http客户端
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 参数
		StringBuffer params= new StringBuffer();
		try{
			// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
			params.append("name="+ URLEncoder.encode("liujun", "utf-8"));
			params.append("&");
			params.append("age=24");
		} catch(UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// 创建Get请求
		HttpGet httpGet= new HttpGet("http://localhost:8888/doGetHttpClintControllerTwo" + "?" + params);

		httpGet.setHeader("Content-Type", "application/json;charset=utf8");
		// 响应模型
		CloseableHttpResponse response= null;
		try{
			// 由客户端执行(发送)Get请求
			response= httpClient.execute(httpGet);
			// 配置信息
			RequestConfig requestConfig= RequestConfig.custom()
			// 设置连接超时时间(单位毫秒)
			.setConnectTimeout(5000)
			// 设置请求超时时间(单位毫秒)
			.setConnectionRequestTimeout(5000)
			// socket读写超时时间(单位毫秒)
			.setSocketTimeout(5000)
			// 设置是否允许重定向(默认为true)
			.setRedirectsEnabled(true).build();
			// 将上面的配置信息 运用到这个Get请求里
			httpGet.setConfig(requestConfig);
			//response.addHeader("Accept-Encoding","gzip, deflate");
			// 从响应模型中获取响应实体
			HttpEntity responseEntity= response.getEntity();
			System.out.println("响应状态为:"+ response.getStatusLine());
			if(responseEntity != null) {
				System.out.println("响应内容长度为:"+ responseEntity.getContentLength());
				System.out.println("响应内容为:"+ EntityUtils.toString(responseEntity,"utf-8"));
			}
		} catch(ClientProtocolException e) {
			e.printStackTrace();
		} catch(ParseException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		} finally{
			try{
				// 释放资源
				if(httpClient != null) {

					httpClient.close();

				}
				if(response != null) {

					response.close();

				}

			} catch(IOException e) {

				e.printStackTrace();

			}

		}
	}

第三步对应接收事例

@Controller
public class doGetController {

    @RequestMapping("doGetHttpClintControllerTwo")
    @ResponseBody
    public String doGetHttpClintControllerTwo(String name, Integer age) {
        String code="没想到"+name+"都"+age+"岁了";
        return code;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值