首页 > 代码库 > java使用httpcomponents发送get请求
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 }
请求成功后,后天会打印返回的信息。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。