java使用httpclient访问接口


前言

本章节使用apache组件下的httpclient来访问分别以GET和POST的方式,模拟请求远程服务的接口。


一、引入包

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

二、代码部分

1.服务方

代码如下(示例):

package com.student.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Random;

/**
 * Create by zjg on 2023/4/27
 */
@RequestMapping("/http/")
@RestController
public class HttpClientController {
    @GetMapping("client")
    public JSONObject get(String province, String city, String area){
        return getWeather(province,city,area,"GET");
    }
    @PostMapping("client")
    public JSONObject post(@RequestBody JSONObject jsonObject){
        return getWeather(jsonObject.getString("province"),jsonObject.getString("city"),jsonObject.getString("area"),"POST");
    }
    public JSONObject getWeather(String province,String city,String area,String type){
        String []weathers={"晴","多云","小雨","中雨","大雨","暴雨"};
        int index= new Random().nextInt(weathers.length);
        JSONObject jsonObject = new JSONObject();
        LocalDate now = LocalDate.now();
        jsonObject.put("weather",province+city+area+" "+now+":"+weathers[index]);
        jsonObject.put("type",type);
        return jsonObject;
    }
}

2.请求方

代码如下(示例):

package test;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Create by zjg on 2023/7/20
 */
public class HttpClientTest {
    public static final String API_URL = "http://127.0.0.1:8080/http/client";

    public static void main(String[] args) {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type","application/json");
        Map<String, Object> bodyMap = new HashMap();
        bodyMap.put("province","山东省");
        bodyMap.put("city","济南市");
        bodyMap.put("area","历城区");
        String result = sendRequest(RequestMethod.GET,API_URL, headerMap, bodyMap);
        System.out.println(result);
        result = sendRequest(RequestMethod.POST,API_URL, headerMap, bodyMap);
        System.out.println(result);
    }
    public static String sendRequest(RequestMethod requestMethod,String url,Map<String, String> headerMap, Map<String, Object> contentMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            switch (requestMethod){
                case GET:response = httpClient.execute(get(url,headerMap,contentMap));break;
                case POST:response = httpClient.execute(post(url,headerMap,contentMap));break;
            }
            String result = null;
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }

    /**
     * 设置超时时间
     * @return
     */
    private static RequestConfig setRequestConfig(int timeOut) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(timeOut)
                .setConnectionRequestTimeout(timeOut)
                .setSocketTimeout(timeOut).build();
        return requestConfig;
    }
    private static HttpUriRequest get(String url, Map<String, String> headerMap, Map<String, Object> contentMap){
        HttpGet httpGet = new HttpGet();
        httpGet.setConfig(setRequestConfig(10000));
        Iterator<Map.Entry<String, String>> headerIterator = headerMap.entrySet().iterator();
        while (headerIterator.hasNext()) {
            Map.Entry<String, String> elem = headerIterator.next();
            httpGet.addHeader(elem.getKey(), elem.getValue());
        }
        if (contentMap!=null&&contentMap.size() > 0) {
            url+="?";
            Iterator<Map.Entry<String, Object>> contentIterator = contentMap.entrySet().iterator();
            while (contentIterator.hasNext()) {
                Map.Entry<String, Object> elem = contentIterator.next();
                url+=elem.getKey()+"="+elem.getValue()+"&";
            }
        }
        httpGet.setURI(URI.create(url.substring(0,url.length()-1)));
        return httpGet;
    }
    private static HttpUriRequest post(String url, Map<String, String> headerMap, Map<String, Object> contentMap){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(setRequestConfig(10000));
        Iterator<Map.Entry<String, String>> headerIterator = headerMap.entrySet().iterator();
        while (headerIterator.hasNext()) {
            Map.Entry<String, String> elem = headerIterator.next();
            httpPost.addHeader(elem.getKey(), elem.getValue());
        }
        if (contentMap!=null&&contentMap.size() > 0) {
            HttpEntity httpEntity = EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setBinary(JSON.toJSONBytes(contentMap)).build();
            httpPost.setEntity(httpEntity);
        }
        return httpPost;
    }
    enum RequestMethod{
        GET,POST;
    }
}

三、执行结果

{“weather”:“山东省济南市历城区 2023-07-20:中雨”,“type”:“GET”}
{“weather”:“山东省济南市历城区 2023-07-20:中雨”,“type”:“POST”}


总结

回到顶部
使用RestTemplate让访问http更加简单。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值