Java-HttpClient

x33g5p2x  于2021-10-08 转载在 Java  
字(11.8k)|赞(0)|评价(0)|浏览(215)

HttpUtils需要的jar 依赖

使用工具类需要导入的maven依赖

<!-- json解析-->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.47</version>
      </dependency>

      <!--http 服务-->
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.3</version>
      </dependency>


      <dependency>
          <groupId>commons-lang</groupId>
          <artifactId>commons-lang</artifactId>
          <version>2.6</version>
      </dependency>

      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
      </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>provided</scope>
    </dependency>

HttpUtils工具类

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;


public class HttpUtils {

    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;
    private static final int MAX_TOTAL = 100;
    private static final int MAX_TIMEOUT = 7000;
    private static final int CONNECT_TIMEOUT = 10000;
    private static final int SOCKET_TIMEOUT = 40000;
    private static final String CHARSET = "UTF-8";

    public HttpUtils() {
    }


    static {
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(100);
        Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(10000);
        configBuilder.setSocketTimeout(40000);
        configBuilder.setConnectionRequestTimeout(7000);
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }




    /** * 发送http请求 get post put delete * get 通过url?name=""&&name="" 发送参数 * pist 和put ,delete 通过请求体发送参数 json格式 */
    public static String httpClient(String postType, String url, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        String result = null;
        try {
            if (postType.equals("Get")) {
                //===== get =====//
                HttpGet httpGet = new HttpGet(url);
                //设置header
                httpGet.setHeader("Content-type", "application/json");
                httpGet.setHeader("DataEncoding", "UTF-8");
                //发送请求
                httpResponse = httpClient.execute(httpGet);
            } else if(postType.equals("Post")) {
                //===== post =====//
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-type", "application/json");
                httpPost.setHeader("DataEncoding", "UTF-8");
                //增加参数
                httpPost.setEntity(new StringEntity(jsonStr.toString(),"UTF-8"));
                httpResponse = httpClient.execute(httpPost);
            } else if(postType.equals("Put")) {
                //===== put =====//
                HttpPut httpPut = new HttpPut(url);
                httpPut.setHeader("Content-type", "application/json");
                httpPut.setHeader("DataEncoding", "UTF-8");
                httpPut.setEntity(new StringEntity(jsonStr.toString(),"UTF-8"));
                httpResponse = httpClient.execute(httpPut);
            } else if (postType.equals("Delete")) {
                //===== delete ===== 不能有参数 //
                HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
                httpDelete.setHeader("Content-type", "application/json");
                httpDelete.setHeader("DataEncoding", "UTF-8");

                StringEntity input = new StringEntity(jsonStr.toString(), ContentType.APPLICATION_JSON);
                httpDelete.setEntity(input);
                httpResponse = httpClient.execute(httpDelete);

            }else{
                result=null;
                System.out.println("没有找到你要的请求");
            }
            //返回结果
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
// 可以实现 delete 请求 body 传输数据
    static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
        public static final String METHOD_NAME = "DELETE";

        public String getMethod() {
            return METHOD_NAME;
        }

        public HttpDeleteWithBody(final String uri) {
            super();
            setURI(URI.create(uri));
        }

        public HttpDeleteWithBody(final URI uri) {
            super();
            setURI(uri);
        }

        public HttpDeleteWithBody() {
            super();
        }
    }

// ------------------------------进阶 get post put delete map集合作为参数 的 请发送


    public static String doGet(String url, Map<String, Object> params) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(url)) {

            return result;
        } else {
            List<NameValuePair> pairList = new ArrayList(params.size());
            Iterator var4 = params.entrySet().iterator();

            while(var4.hasNext()) {
                Entry<String, Object> entry = (Entry)var4.next();
                NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }

            CloseableHttpResponse response = null;
            InputStream instream = null;
            CloseableHttpClient httpclient = HttpClients.createDefault();

            try {
                URIBuilder URIBuilder = new URIBuilder(url);
                System.out.println(pairList);
                URIBuilder.addParameters(pairList);
                URI uri = URIBuilder.build();
                System.out.println(uri);
                HttpGet httpGet = new HttpGet(uri);
                response = httpclient.execute(httpGet);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    instream = entity.getContent();
                    result = IOUtils.toString(instream, "UTF-8");
                }
            } catch (IOException | URISyntaxException ignored) {

            } finally {
                if (null != instream) {
                    instream.close();
                }

                if (null != response) {
                    response.close();
                }

                if (null != httpclient) {
                    httpclient.close();
                }

            }

            return result;
        }
    }


    // post请求
    public static String doPost(String url, Map<String, Object> map) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(url)) {

            return result;
        } else {


            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpResponse response = null;
            InputStream instream = null;

            try {

                httpPost.setHeader("Content-type", "application/json");
                httpPost.setHeader("DataEncoding", "UTF-8");

                httpPost.setConfig(requestConfig);
                Object o = JSON.toJSON(map);
                httpPost.setEntity( new StringEntity(o.toString(), "UTF-8"));
                response = httpClient.execute(httpPost);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    instream = entity.getContent();
                    result = IOUtils.toString(instream, "UTF-8");

                }
            } catch (IOException var14) {

            } finally {
                if (null != instream) {
                    instream.close();
                }

                if (null != response) {
                    response.close();
                }

                if (null != httpClient) {
                    httpClient.close();
                }

            }

            return result;
        }
    }


    // Put请求
    public static String doPut(String url, Map<String, Object> map) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(url)) {

            return result;
        } else {


            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPut HttpPut = new HttpPut(url);
            CloseableHttpResponse response = null;
            InputStream instream = null;

            try {

                HttpPut.setHeader("Content-type", "application/json");
                HttpPut.setHeader("DataEncoding", "UTF-8");

                HttpPut.setConfig(requestConfig);
                Object o = JSON.toJSON(map);
                HttpPut.setEntity( new StringEntity(o.toString(), "UTF-8"));
                response = httpClient.execute(HttpPut);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    instream = entity.getContent();
                    result = IOUtils.toString(instream, "UTF-8");

                }
            } catch (IOException var14) {

            } finally {
                if (null != instream) {
                    instream.close();
                }

                if (null != response) {
                    response.close();
                }

                if (null != httpClient) {
                    httpClient.close();
                }

            }

            return result;
        }
    }

    // Delete 请求
    public static String doDelete(String url, Map<String, Object> map) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(url)) {

            return result;
        } else {


            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpDeleteWithBody HttpDelete = new HttpDeleteWithBody(url);
            CloseableHttpResponse response = null;
            InputStream instream = null;

            try {

                HttpDelete.setHeader("Content-type", "application/json");
                HttpDelete.setHeader("DataEncoding", "UTF-8");

                HttpDelete.setConfig(requestConfig);
                Object o = JSON.toJSON(map);
                HttpDelete.setEntity( new StringEntity(o.toString(), "UTF-8"));
                response = httpClient.execute(HttpDelete);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    instream = entity.getContent();
                    result = IOUtils.toString(instream, "UTF-8");

                }
            } catch (IOException var14) {

            } finally {
                if (null != instream) {
                    instream.close();
                }

                if (null != response) {
                    response.close();
                }

                if (null != httpClient) {
                    httpClient.close();
                }

            }

            return result;
        }
    }

  
}

测试

自己搭建 SpringMVC环境 或者SpringBoot环境

HttpUtils_test_Controller

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@RestController
@RequestMapping("/http")
public class HttpUtils_test_Controller {

    @GetMapping
    @ResponseBody
    public String  Get(HttpServletRequest request){
        Enumeration<String> parameterNames = request.getParameterNames();
        String json="{";
        while (parameterNames.hasMoreElements()){
            String s = parameterNames.nextElement();
            String parameter = request.getParameter(s);
            System.out.println("key"+s+"____"+"value"+parameter);
            json+=s+":"+parameter+",";

        }
       json= json.substring(0,json.length()-2)+"}";
        return  json;
    }

    @PostMapping
    @ResponseBody
    public String Post(@RequestBody String body){
        System.out.println("请求体"+body);
        return body;
    }
    @PutMapping
    @ResponseBody
    public String Put(@RequestBody String body){
        System.out.println("请求体"+body);
        return body;
    }
    @DeleteMapping
    @ResponseBody
    public String Delete(@RequestBody String body){
        System.out.println("请求体"+body);
        return body;
    }
}

测试代码

@Test
    public void get(){
        String s = HttpUtils.httpClient("Get", "http://localhost:20210/http?name=123&&pass=123", null);
        System.out.println("返回的结果");
        System.out.println(s);
    }

    @Test
    public void post(){
        String json="{\"name\":\"你好\"}";

        String s = HttpUtils.httpClient("Post", "http://localhost:20210/http", json);
        System.out.println("返回的结果");
        System.out.println(s);
    }

    @Test
    public void put(){
        String json="{\"num\":\"12\"}";

        String s = HttpUtils.httpClient("Put", "http://localhost:20210/http", json);
        System.out.println("返回的结果");
        System.out.println(s);
    }

    @Test
    public void delete(){
        String json="{\"num\":\"15\"}";
        String s = HttpUtils.httpClient("Delete", "http://localhost:20210/http", json);
        System.out.println("返回的结果");
        System.out.println(s);
    }







    @Test
    public void getMap() throws Exception {
        Map  map=new HashMap();
        map.put("name","123");
        map.put("name1","1233");
        String s = HttpUtils.doGet("http://localhost:20210/http", map);
        System.out.println("返回的结果");
        System.out.println(s);
    }
    @Test
    public void PostMap() throws Exception {
        Map  map=new HashMap();
        map.put("name","123");
        map.put("name1","1233");
        String s = HttpUtils.doPost("http://localhost:20210/http", map);
        System.out.println("返回的结果");
        System.out.println(s);
    }
    @Test
    public void PutMap() throws Exception {
        Map  map=new HashMap();
        map.put("bbb","123");
        map.put("aaaa","1233");
        String s = HttpUtils.doPut("http://localhost:20210/http", map);
        System.out.println("返回的结果");
        System.out.println(s);
    }

    @Test
    public void DeleteMap() throws Exception {
        Map  map=new HashMap();
        map.put("ccc","123");
        map.put("eee","1233");
        String s = HttpUtils.doDelete("http://localhost:20210/http", map);
        System.out.println("返回的结果");
        System.out.println(s);
    }

相关文章

微信公众号

最新文章

更多