java使用httpclient访问接口

文章目录

  • 前言
  • 一、引入包
  • 二、代码部分
    • 1.服务方
    • 2.请求方
  • 三、执行结果
  • 总结


前言

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


一、引入包


<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.13version>
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”}


总结

回到顶部

你可能感兴趣的:(java,java,开发语言)