httpclient4.5.2 Post请求支持http和https

先导入所需的jar包,pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

 

写一个工具类 HttpUtil

package cn.nintendoswitch.user.api.boot.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients;


public class HttpUtil {

    public static String doPost(String url, Header[] headers, Map<String, Object> paramMaps) {
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        try {
            httpPost.setHeaders(headers);
            List<NameValuePair> pairList = new ArrayList<>();
            for (Map.Entry<String, Object> entry : paramMaps.entrySet()) {
                String key = entry.getKey();
                String value = (String) entry.getValue();
                pairList.add(new BasicNameValuePair(key, value));
            }
            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(pairList, "UTF-8");
            httpPost.setEntity(urlEntity);
            HttpResponse resp = closeableHttpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
            }
        } catch (Exception e) {
            throw new RuntimeException("HTTP post failed.", e);
        } finally {
            httpPost.abort();
            try {
                closeableHttpClient.close();
            } catch (Exception e2) {
                throw new RuntimeException("Close CloseableHttpClient failed.", e2);
            }
        }
        
        return result;
    }


// 使用代理服务器IP 请求出去
public static String doHttpsPost(String url, Header[] headers, Map<String, Object> paramMaps) {
// 设置代理
HttpHost proxy = new HttpHost(代理IP, 端口号, "http");
RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();

String result = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = new HttpPost(url);
try {
    httpPost.setHeaders(headers);
         httpPost.setEntity(httpEntity);
         httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
         HttpResponse resp = httpClient.execute(httpPost);
         result = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
} catch (Exception e) {
throw new RuntimeException("HTTP Post failed.", e);
} finally {
        httpPost.abort();
        try {
            httpClient.close();
        } catch (IOException e) {
            throw new RuntimeException("Close CoseabledHttpClient failed.", e);
        }
}
return result;
}


}

 

 

 

 

写个测试调用方法:

package cn.nintendoswitch.user.api.boot.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.nintendoswitch.user.api.boot.common.util.HttpUtil;
import io.jsonwebtoken.impl.Base64Codec;

@Controller
public class IndexController {
    
    @RequestMapping("/indexPage")
    public void indexPage(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("welcome to shanghai.");
    }
    
    @RequestMapping("/testPostWaveToken")
    public void testPostWaveToken(HttpServletRequest request, HttpServletResponse response) {
        String url = "https://xxxxxx.com.cn/aaa/bbb/";
        
        String base64Content = "12121212121:aaaaaaaaaaaaa";
        String encodeContent = Base64Codec.BASE64.encode(base64Content);
        Header[] headers = {new BasicHeader("token", "ABCDEF " + encodeContent),
                new BasicHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE)};
        Map<String, Object> paramMaps = new HashMap<>();
        paramMaps.put("param01", "value01");
        String resutlMsg = HttpUtil.doPost(url, headers, paramMaps);
        System.out.println("return info is : " + resutlMsg);
    }
}

 

好了,备忘一下,需要的朋友可以转载,但请注明原著来源,谢谢。

 

posted @ 2019-07-04 20:16  JimmyShan  阅读(2548)  评论(0编辑  收藏  举报