https工具类设置请求头,使用apache的httpclient实现

https工具类设置请求头,使用apache的httpclient实现,第1张

 在项目开发过程中,我想大部分系统都需要对接另外的系统。对接方式有很多种,现在最常见的就是https请求了。现将Java发送https请求的工具类整理一下,有需要用到的同学拿走不谢。

  该方法使用apache的httpclient实现

第一步:创建SSLClient

import java.security.cert.CertificateException

import java.security.cert.X509Certificate

import javax.net.ssl.SSLContext

import javax.net.ssl.TrustManager

import javax.net.ssl.X509TrustManager

import org.apache.http.conn.ClientConnectionManager

import org.apache.http.conn.scheme.Scheme

import org.apache.http.conn.scheme.SchemeRegistry

import org.apache.http.conn.ssl.SSLSocketFactory

import org.apache.http.impl.client.DefaultHttpClient

public class SSLClient extends DefaultHttpClient{

public SSLClient() throws Exception{

super()

SSLContext ctx = SSLContext.getInstance("TLS")

X509TrustManager tm = new X509TrustManager() {

@Override

public void checkClientTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

@Override

public void checkServerTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

@Override

public X509Certificate[] getAcceptedIssuers() {

return null

}

}

ctx.init(null, new TrustManager[]{tm}, null)

SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)

ClientConnectionManager ccm = this.getConnectionManager()

SchemeRegistry sr = ccm.getSchemeRegistry()

sr.register(new Scheme("https", 443, ssf))

}

}

第二步:实现自己的https工具类

import org.apache.http.HttpEntity

import org.apache.http.HttpResponse

import org.apache.http.client.HttpClient

import org.apache.http.client.methods.HttpGet

import org.apache.http.client.methods.HttpPost

import org.apache.http.entity.StringEntity

import org.apache.http.message.BasicHeader

import org.apache.http.protocol.HTTP

import org.apache.http.util.EntityUtils

import java.util.Map

public class HttpsClientUtil {

private static final String CHAREST = "utf-8"

/**

* 发送post请求

* @param url

* @return

*/

public static String doPost(String url,String mapParam){

HttpClient httpClient = null

HttpPost httpPost = null

String result = null

try{

httpClient = new SSLClient()

httpPost = new HttpPost(url)

//设置参数

httpPost.setHeader("Content-Type", "application/json")

httpPost.addHeader("Authorization", "Basic YWRtaW46")

StringEntity s = new StringEntity(mapParam, CHAREST)

s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"))

httpPost.setEntity(s)

HttpResponse response = httpClient.execute(httpPost)

if(response != null){

HttpEntity resEntity = response.getEntity()

if(resEntity != null){

result = EntityUtils.toString(resEntity,CHAREST)

}

}

}catch(Exception ex){

ex.printStackTrace()

}

return result

}

/**

* 发送get请求

* @param url      链接地址

* @return

*/

public static String doGet(String url){

HttpClient httpClient = null

HttpGet httpGet= null

String result = null

try {

httpClient = new SSLClient()

httpGet = new HttpGet(url)

HttpResponse response = httpClient.execute(httpGet)

if(response != null){

HttpEntity resEntity = response.getEntity()

if(resEntity != null){

result = EntityUtils.toString(resEntity,CHAREST)

}

}

} catch (Exception e) {

e.printStackTrace()

}

return result

}

/**

* 发送get请求,并设置get的请求头

* @param url      链接地址

* @return

*/

public static String setHeadDoGet(String url,Map headers){

HttpClient httpClient = null

HttpGet httpGet= null

String result = null

try {

httpClient = new SSLClient()

httpGet = new HttpGet(url)

for (Map.Entry e : headers.entrySet()) {

httpGet.addHeader(e.getKey(), e.getValue())

}

HttpResponse response = httpClient.execute(httpGet)

if(response != null){

HttpEntity resEntity = response.getEntity()

if(resEntity != null){

result = EntityUtils.toString(resEntity,CHAREST)

}

}

} catch (Exception e) {

e.printStackTrace()

}

return result

}

}

ps:有需要设置post请求头的请求,同学们可以参考setHeadDoGet方法进行编写。 需要用到的apache的httpclient-4.5.9.jar包 。

首先,我们先看一下http的头信息到底是什么:

HTTP(HyperTextTransferProtocol) 即超文本传输协议,目前网页传输的的通用协议。HTTP协议采用了请求/响应模型,浏览器或其他客户端发出请求,服务器给与响应。就整个网络资源传输而 言,包括message-header和message-body两部分。首先传递message- header,即http header消息。http header 消息通常被分为4个部分: general header, request header, response header, entity header。但是这种分法就理解而言,感觉界限不太明确,根据日常使用,大体分为Request和Response两部分。

在通常的servlet/jsp应用中,我们只是从http的header中取得信息,如果要设置信息,需要用到HttpClient,具体的设置方法如下:

HttpResponse response = null

HttpGet get = new HttpGet(url)

get.addHeader("Accept", "text/html")

get.addHeader("Accept-Charset", "utf-8")

get.addHeader("Accept-Encoding", "gzip")

get.addHeader("Accept-Language", "en-US,en")

get.addHeader("User-Agent", "Mozilla/5.0 (X11Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22")

response = client.execute(get)

HttpEntity entity = response.getEntity()

Header header = entity.getContentEncoding()

if (header != null)

{

HeaderElement[] codecs = header.getElements()

for (int i = 0i <codecs.lengthi++)

{

if (codecs[i].getName().equalsIgnoreCase("gzip"))

{

response.setEntity(new GzipDecompressingEntity(entity))

}

}

}

return response

其中,client为一个HttpClient的实力,创建方式如:

SchemeRegistry schemeRegistry = new SchemeRegistry()

schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()))

schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()))

PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry)

cm.setMaxTotal(200)

cm.setDefaultMaxPerRoute(2)

HttpHost googleResearch = new HttpHost("research.google.com", 80)

HttpHost wikipediaEn = new HttpHost("en.wikipedia.org", 80)

cm.setMaxPerRoute(new HttpRoute(googleResearch), 30)

cm.setMaxPerRoute(new HttpRoute(wikipediaEn), 50)

DefaultHttpClient client = new DefaultHttpClient(cm)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11086286.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存