HttpClient请求另一个系统接口接收数据

本文详细介绍如何使用HTTPClient发起GET请求,从封装HTTPClient的方法开始,到系统间通过GET请求进行数据交互的具体实现。文章提供了代码示例,包括依赖包的配置、GET请求的封装、接口数据的返回与接收处理。

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

使用HttpClient接受另一个系统接口提供的数据

本文适用于新手不会使用httpclient请求接口的情况,大神请别闹

httpclient介绍

自行百度,这里不做介绍

第一步,先封装httpclient

这里仅封装get请求,post同理,自行百度

  public static String doGet(String url, Map<String, String> param) {  
        // 创建Httpclient对象  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
  
        String resultString = "";  
        CloseableHttpResponse response = null;  
        try {  
            // 创建uri  
            URIBuilder builder = new URIBuilder(url);  
            if (param != null) {  
                for (String key : param.keySet()) {  
                    builder.addParameter(key, param.get(key));  
                }  
            }  
            URI uri = builder.build();  
  
            // 创建http GET请求  
            HttpGet httpGet = new HttpGet(uri);  
  
            // 执行请求  
            response = httpclient.execute(httpGet);  
            // 判断返回状态是否为200  
            if (response.getStatusLine().getStatusCode() == 200) {  
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return resultString;  
    }  
  
    public static String doGet(String url) {  
        return doGet(url, null);  
    }  

第二步,系统一提供接口返回数据

@RequestMapping(value="/list", method = RequestMethod.GET)

	@ResponseBody
	public JSONArray queryNewIpPatient(){
		//自己的接口
		List<Student> list=studentSrvInf.getAllStudent();
		if (list.size()>0){
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
			System.out.println(jsonArray);
			return jsonArray;
		}else {
			return null;
		}
	}

第三步,系统二接收系统一接口返回数据并处理

public void getPost()throws Exception{

       
        //接受get请求返回的参数,此处直接输出到页面可能会乱码
        String s= HttpClientUtil.doGet("http://127.0.0.1:8080/list");
        //封装成jsonArray之后就不会乱码了嘻嘻
        JSONArray Json= JSONArray.fromObject(s);
        //遍历方法
        for(int i=0;i<Json.size();i++){
        	//括号里为返回的json数组中的对象的属性名,具体可以将json打印出来查看
            String name=Json.get(i).getString("name");
        }
    }

依赖包:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
Apache HttpClient库在版本4.5.13中并不直接提供接口来生成URL并接收数据,它主要用于HTTP客户端请求。但是,你可以通过它的API构建一个`HttpGet`或`HttpPost`实例,然后发送请求到指定的URL去接收数据。 以下是一个基本的例子,展示如何使用`HttpGet`来获取远程资源: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 生成一个GET请求的URL String apiUrl = "http://example.com/api/data"; // 替换为你需要的实际地址 // 创建HttpGet请求 HttpGet get = new HttpGet(apiUrl); // 发送请求获取响应 CloseableHttpResponse response = httpClient.execute(get); try { // 检查状态码,如果成功则读取响应体 int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String responseData = EntityUtils.toString(entity, "UTF-8"); System.out.println("Received data: " + responseData); } else { System.out.println("Request failed with status code: " + statusCode); } } finally { response.close(); } } finally { httpClient.close(); } } } ``` 要接收数据,你需要替换`apiUrl`变量为你要访问的接口地址。注意,这是一个基础示例,实际生产环境中可能需要处理更复杂的错误情况以及使用异常处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值