httpcomponents:几种常见的http请求,get/post

1.添加mvn依赖

 <dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
 </dependency>
 <dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.8</version>
 </dependency>
 <dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.6</version>
 </dependency>

 2.封装实现几种常见的http请求

package com.luck.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class HttpUtil {

    private static Logger logger = Logger.getLogger(HttpUtil.class);

    public static String doGet(String url, Map<String,String> map) {
        HttpGet httpGet = null;
        if (map == null || map.size() == 0) {
            httpGet = new HttpGet(url);
            logger.info("【send】【doGet】无参 url:" + url);
        } else {
            try {
                URIBuilder uriBuilder = new URIBuilder(url);
                map.forEach((k, v) -> {
                    uriBuilder.addParameter(k, v);
                });
                URI build = uriBuilder.build();
                httpGet = new HttpGet(build);
                logger.info("【send】【doGet】有参 url:" + build.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 json
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        logger.info("【send】【doPost】json, url:" + url + ",参数:" + json);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        CloseableHttpResponse response = null;
        try {
            StringEntity stringEntity = new StringEntity(json,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            result =  EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * POST 请求 Form
     * @param url
     * @param map
     * @return
     */
    public static String doPostForm(String url, Map<String, String> map) {
        logger.info("【send】【doPost】form, url:" + url + ",参数:" + map);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        map.forEach((k, v) -> {
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair(k, v);
            nameValuePairs.add(basicNameValuePair);
        });
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 Form/上传图片
     * @param url
     * @param map
     * @param file
     * @return
     */
    public static String doPostFormData(String url, Map<String, String> map, MultipartFile file) {
        logger.info("【send】【doPost】formData, url:" + url + ",参数:" + map + "," + file);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.APPLICATION_JSON;
        entityBuilder.setCharset(contentType.getCharset());
        map.forEach((k, v) -> {
            entityBuilder.addTextBody(k, v, contentType);
        });
        String result = null;
        CloseableHttpResponse response = null;
        try {
            entityBuilder.addBinaryBody(file.getName(), file.getBytes(), ContentType.create("multipart/form-data"), file.getName());
            httpPost.setEntity(entityBuilder.build());
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 无规则字符
     * @param url
     * @param text
     * @return
     */
    public static String doPostText(String url, String text) {
        logger.info("【send】【doPost】Text, url:" + url + ",参数:" + text);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        ContentType contentType = ContentType.create("text/plain", "UTF-8");
        StringEntity stringEntity = new StringEntity(text, contentType);
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 根据url 返回 byte[]
     * @param url
     * @return
     * @throws IOException
     */
    public static byte[] UrlGetBytes(String url) {
        URLConnection urlConnection;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] byteArray = null;
        try {
            urlConnection = new URL(url).openConnection();
            inputStream = urlConnection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int n;
            while (-1 != (n = inputStream.read(bytes))) {
                outputStream.write(bytes, 0, n);
            }
            byteArray = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArray;
    }

    /**
     * 将url 内容保存到 本地路径
     * @param url
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean UrlSaveToPath(String path, String url) {
        byte[] bytes = HttpUtil.UrlGetBytes(url);
        return HttpUtil.BytesSaveToPath(path, bytes);
    }

    /**
     * 将bytes 内容保存到 本地路径
     * @param path
     * @param bytes
     * @return
     */
    public static boolean BytesSaveToPath(String path, byte[] bytes) {
        if (StringUtils.isEmpty(path) || bytes == null || bytes.length == 0) {
            return false;
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    
}

 3.controller

package com.luck;

import com.luck.model.dto.BlogInfoDto;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/httpController")
public class HttpController {

    private Logger logger = Logger.getLogger(HttpController.class);

    /**
     * GET
     * @param value
     * @return
     */
    @GetMapping("/doGet")
    public String doGet(@RequestParam("value") String value) {
        logger.info("http:success doGet>>." + value);
        return "请求以收到 doGet().";
    }

    /**
     * POST : JSON
     * json字符串
     * @param blogInfoDto
     * @return
     */
    @PostMapping(value = "/doPostJson", produces = "application/json;charset=utf-8")
    public String doPostJson(@RequestBody BlogInfoDto blogInfoDto) {
        logger.info("http:success doPost>>type:json,request:" + blogInfoDto);
        return "请求以收到 doPostJson.";
    }

    /**
     * POST : FORM
     * 表单提交
     * @param blogInfoDto
     * @return
     */
    @PostMapping(value = "/doPostForm", produces = "application/x-www-form-urlencoded")
    public String doPostForm(BlogInfoDto blogInfoDto) {
        logger.info("http:success doPost>>type:Form,request:" + blogInfoDto);
        return "请求以收到 doPostForm.";
    }

    /**
     * POST : FORM-DATA
     * 表单提交 + 上传文件
     * @param blogInfoDto
     * @param file
     * @return
     */
    @PostMapping(value = "/doPostFormData", produces = "multipart/form-data;charset=utf-8")
    public String doPostFormData(BlogInfoDto blogInfoDto, @RequestParam("imgFile") MultipartFile file) {
        logger.info("http:success doPost>>type:FormData,request:" + blogInfoDto + ",文件名:" + file.getName());
        return "请求以收到 doPostFormData.";
    }

    /**
     * POST : TEXT
     * 纯文本
     * @param values
     * @return
     */
    @PostMapping(value = "/doPostText", produces = "text/plain")
    public String doPostText(@RequestBody String values) {
        logger.info("http:success doPost>>type:Text,request:" + values);
        return "请求以收到 doPostText.";
    }

}

4.测试类

package com.luck.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.mock.web.MockMultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class TestHttp {
    public static void main(String[] args) {
        doGet();
        doPostJson();
        doPostForm();
        doPostFormData();
        doPostText();
    }
    public static void doPostText() {
        String result = HttpUtil.doPostText("http://localhost:8082/httpController/doPostText", "啊哈哈");
        System.out.println(result);
    }
    public static void doPostFormData() {
        Map map = new HashMap<>();
        map.put("userName","华为");
        MockMultipartFile mockMultipartFile = null;
        try {
            FileInputStream fileInputStream = new FileInputStream("C:\\Users\\14296\\Pictures\\Camera Roll\\1.jpg");
            mockMultipartFile = new MockMultipartFile("imgFile", fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = HttpUtil.doPostFormData("http://localhost:8082/httpController/doPostFormData", map, mockMultipartFile);
        System.out.println(result);
    }
    public static void doPostForm() {
        Map map = new HashMap<>();
        map.put("userName","华为");
        String result = HttpUtil.doPostForm("http://localhost:8082/httpController/doPostForm", map);
        System.out.println(result);
    }
    public static void doPostJson(){
        Map map = new HashMap<>();
        map.put("userName","华为");
        JSONObject jsonObject = new JSONObject(map);
        String s = jsonObject.toString();
        String result = HttpUtil.doPostJson("http://localhost:8082/httpController/doPostJson", s);
        System.out.println(result);
    }
    public static void doGet(){
        Map map = new HashMap<>();
        map.put("value","传参了");
        String result = HttpUtil.doGet("http://localhost:8082/httpController/doGet", map);
        System.out.println(result);
    }
}

 欧也!希望多多指出不知与缺陷,谢谢!嘿嘿!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值