Http请求工具

Http请求工具


GET,POST请求


import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
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.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.*;public class HttpUtil {
private static Certificate cert = null;
private static SSLConnectionSocketFactory socketFactory;//私密连接工厂
private static TrustManager manager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
/**
* 是否忽略证书.https网站一般情况下使用了安全系数较低的SHA-1签名,因此首先我们在调用SSL之前需要重写验证方法,取消检测SSL。
*/
private static void enableSSl(boolean isIgnore) {
try {
SSLContext context = SSLContext.getInstance("TLS");
if (isIgnore) {
context.init(null, new TrustManager[]{manager}, null);
} else {
context.init(null, new TrustManager[]{httpsManager}, null);
}
socketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier
.INSTANCE);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
/**
* 证书获取
*
* @param certificateUrl 证书地址.
*/
private static void initHttpsCertificate(String certificateUrl) {
try {
FileInputStream fis = new FileInputStream(certificateUrl);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
cert = cf.generateCertificate(bis);
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
}
private static TrustManager httpsManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{(X509Certificate) cert};
}
};
/**
* httpClient get http 请求.
*
* @param url    请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String doGet(String url, List<NameValuePair> values) throws IOException {
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
//最新版的httpClient使用实现类的是closeableHTTPClient,以前的default作废了.设置可关闭的httpclient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
StringBuilder urlBuffer = new StringBuilder(url);
if (!url.contains("?")) {
urlBuffer.append("?");
}
if (values != null) {
for (NameValuePair nameValuePair : values) {
urlBuffer.append("&").append(nameValuePair.getName()).append("=")
.append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
}
}
HttpGet get = new HttpGet(urlBuffer.toString());
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}
/**
* httpClient post http 请求.
*
* @param url    请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String doPost(String url, List<NameValuePair> values) throws IOException {
/*Map<String,String> paramMap = new HashMap<String, String>();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (Map.Entry<String,String> entry : paramMap.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}*/
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, "UTF-8");
//StringEntity entity = new StringEntity(values);
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* httpClient post http 请求.
*
* @param url
* @param values
* @param charset
* @return
* @throws IOException
*/
public static String doPost(String url, List<NameValuePair> values, String charset) throws IOException {
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (charset == null) {
charset = "UTF-8";
}
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, charset);
//StringEntity entity = new StringEntity(values);
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* httpClient get https 请求.
*
* @param url    请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String ignoreGetForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL) throws
IOException {
enableSSl(isIgnoreSSL);
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
//创建可用Scheme
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
StringBuilder urlBuffer = new StringBuilder(url);
if (!url.contains("?")) {
urlBuffer.append("?");
}
if (values != null) {
for (NameValuePair nameValuePair : values) {
urlBuffer.append("&").append(nameValuePair.getName()).append("=")
.append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
}
}
HttpGet get = new HttpGet(urlBuffer.toString());
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}
/**
* httpClient get https 请求.
*
* @param url 请求路径.
* @return response 请求结果状态.
*/
public static String ignoreGetForHttps(String url, boolean isIgnoreSSL) throws
IOException {
enableSSl(isIgnoreSSL);
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
//创建可用Scheme
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}    /**
* httpClient post https 请求.
*
* @param url    请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String ignorePostForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL)
throws IOException {
enableSSl(isIgnoreSSL);
//首先设置全局的标准cookie策略
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Charset.forName("UTF-8"));
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* 获取请求返回值.
*/
private static String getResponseContent(CloseableHttpResponse response)
throws IOException {
StringBuilder returnBuffer = new StringBuilder();
BufferedReader reader = null;
try {
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity httpEntity = response.getEntity();
httpEntity = new BufferedHttpEntity(httpEntity);
return EntityUtils.toString(httpEntity);
}
} finally {
response.close();
}
return null;
}
}

转载于:https://www.cnblogs.com/lovellll/p/10222493.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/101222.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 对 FLAG_ACTIVITY_NEW_TASK、FLAG_ACTIVITY_CLEAR_TOP、FLAG_ACTIVITY_SINGLE_TOP 的理解

    对 FLAG_ACTIVITY_NEW_TASK、FLAG_ACTIVITY_CLEAR_TOP、FLAG_ACTIVITY_SINGLE_TOP 的理解为了看得更清晰,以下使用代称newtask:FLAG_ACTIVITY_NEW_TASKcleartop:FLAG_ACTIVITY_CLEAR_TOPsingletop:FLAG_ACTIVITY_SINGLE_TOP文章目录default单独singletop单独cleartopcleartop+singletopnewtask单独newtasknewtask+sin…

  • jsp网页在浏览器中不显示图片_eclipse环境下配置tomcat中jsp项目的虚拟路径[通俗易懂]

    遇到的问题是这样的,在jsp网页中嵌入了本地的图片,由于会用到上传到服务器的图片,所以没有放到项目里面,而是把所有图片单独放到一个文件夹里,然后打算使用绝对路径把要显示的图片显示出来,比如是放在了E盘的uploadPhotos文件夹里,但是在使用绝对路径显示时,代码如下:在eclipse中的内置浏览器里面是可以显示的,但是到其他浏览器都不显示,后来看到这篇文章http://bbs.csdn.net

  • awk基本用法简介

    awk基本用法简介之前说过sed,今天来说awk,它也是一个文本处理器,是linux下的一个命令,比sed更强大。搞linux开发,尤其是后台开发,这个命令几乎必须要用到。awk这三个字母分别代表其三位作者的名字,而不是某个/某些有意义单词的缩写。还是那句话,以实践操作为荣,以只看不练为耻。当然,理解awk的原理是必须的:读入有’\n’换行符分割的一条记录,将记录按指定的域分隔符划分域,$0表示所有域,$1表示第一个域,$n表示第n个域。默认域分隔符是空格键或tab键。

  • 单周期CPU中的指令周期就是一个时钟周期_指令周期和时钟周期的关系

    单周期CPU中的指令周期就是一个时钟周期_指令周期和时钟周期的关系指令周期: CPU每取出并执行一条指令所需的全部时间叫指令周期,也即CPU完成一条指令的时间叫指令周期一般一条完整的指令包括:取指周期、间址周期、执行周期、中断周期。JMPX:该指令的指令周期只有取指周期。ADDX:该指令只有取指周期、执行周期。一个指令周期包含的机器周期个数亦与指令所要求的动作有关,如单操作数指令,只需要一个取操作数周期,而双操作数指令需要两个取操作数周期。实…

    2022年10月13日
  • pycharm python interpreter_python中assertionerror解决

    pycharm python interpreter_python中assertionerror解决Python里SQLAlchemy运行时报错InvalidRequestE:VARCHAR requires a length on dialect mysql

  • python模块有哪些_error loading package list:pypi

    python模块有哪些_error loading package list:pypipython将自己写的模块上传到PyPI服务器,报错error:<urlopenerror[SSL:CERTIFICATE_VERIFY_FAILED]certificatever

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号