HttpUtil

package com.cmb.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
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.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.message.BasicHeader;
import org.junit.rules.Timeout;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class HttpUtil {
    private CloseableHttpClient httpClient;
    private static RequestConfig requestConfig;
    private static final int HTTP_CONNECTION_TIMEOUT_DEFAULT = 2000;
    private static final int HTTP_RESPONSE_TIMEOUT_DEFAULT = 2000;
    private static List
headers; static{ requestConfig = RequestConfig.custom() //设置连接超时时间 .setConnectTimeout(HTTP_CONNECTION_TIMEOUT_DEFAULT) //设置相应的超时时间 .setSocketTimeout(HTTP_RESPONSE_TIMEOUT_DEFAULT) .build(); headers = new ArrayList<>(); headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8")); headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, x-gzip, deflate")); headers.add(new BasicHeader(HttpHeaders.CONNECTION, "keep-alive")); } @PostConstruct public void init(){ // httpClient = HttpClients.createDefault(); httpClient = HttpClients.custom() .setDefaultHeaders(headers) .setDefaultRequestConfig(requestConfig) .build(); } public CloseableHttpResponse getRequest(String uri) throws IOException { HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = httpClient.execute(httpGet); return response; } public CloseableHttpResponse postRequest(String uri,Object javaBean) throws IOException { HttpPost httpPost = new HttpPost(uri); ObjectMapper mapper = new ObjectMapper(); String jsonStr = mapper.writeValueAsString(javaBean); StringEntity entity = new StringEntity(jsonStr); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); return response; } public static void main(String[] args) { Map map = new HashMap<>(); map.put("name","wfl"); String uri = "http://127.0.0.1:8080/test/post"; try{ HttpUtil httpUtil = new HttpUtil(); CloseableHttpResponse response = httpUtil.postRequest(uri,map); if("200".equals(response.getStatusLine())){ System.out.println("请求成功"); HttpEntity httpEntity = response.getEntity(); System.out.println("相应内容为"+httpEntity.getContent()); } }catch (Exception e){ System.out.println("发送post请求时异常"); } } }

http工具类

你可能感兴趣的:(java,https)