java使用httpcomponents发送get请求

一、适用场景

  在ESTful webservice中,get方法一般都是用来获取数据。我们可以使用httpcomponents组件来完成调用。

  如我们需要发起get请求,携带的参数都是附加到请求的url后面。

  url:"http://www.xxxxx.com/message?id=000010"

二、代码示例

 

 1 package com.demo.test;
 2 
 3 import java.io.IOException;
 4 
 5 import org.apache.http.HttpEntity;
 6 import org.apache.http.HttpStatus;
 7 import org.apache.http.client.ClientProtocolException;
 8 import org.apache.http.client.methods.CloseableHttpResponse;
 9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.impl.client.CloseableHttpClient;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.util.EntityUtils;
13 
14 public class Test2 {
15 
16     public static String sendInfo(String url, String param) {
17         String geturl = String.format("%s?id=%s", url, param);
18         CloseableHttpClient client = HttpClients.createDefault();
19         HttpGet get = new HttpGet(geturl);
20         String responseContent = null; // 响应内容
21         CloseableHttpResponse response = null;
22         try {
23             response = client.execute(get);
24             HttpEntity entity = response.getEntity();// 响应体
25             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 正确返回
26                 responseContent = EntityUtils.toString(entity, "UTF-8");
27             }
28         } catch (ClientProtocolException e) {
29             e.printStackTrace();
30         } catch (IOException e) {
31             e.printStackTrace();
32         } finally {
33             try {
34                 if (response != null)
35                     response.close();
36                 if (client != null)
37                     client.close();
38             } catch (IOException e) {
39                 e.printStackTrace();
40             }
41         }
42         return responseContent;
43     }
44 
45     public static void main(String[] args) {
46         String param = "000010";
47         String result = sendInfo("http://www.xxxxx.com/message", param);
48         System.out.println(result);
49     }
50 }

  请求成功后,后天会打印返回的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值