java http 客户端 服务端_JAVA 服务端模拟客户端请求http/https

本文介绍如何使用Java实现HTTP和HTTPS的客户端与服务端交互,包括POST和GET请求,以及HTTPS的查询操作。代码示例中展示了使用Apache HttpClient库进行HTTP请求,以及自定义的HTTPS请求方法。
摘要由CSDN通过智能技术生成

涉及的包:httpcore-4.3.1.jar,httpclient-4.3.2.jar,httpmime-4.3.2.jar,htmlparser.jar,htmllexer.jar

/*

*/

package com.***.app.mappextend.impl.util;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import com.ygsoft.ecp.service.log.EcpLogFactory;

import com.ygsoft.ecp.service.log.IEcpLog;

/**

* POST HTTP JSON请求.

* @author liupeifeng mapengfei

* @version 1.0.0 2016-05-19

* @see

* @since JDK 1.5.0

*/

public class HttpAccessUtil {

/**

* 日志文件

*/

private static final IEcpLog LOG = EcpLogFactory.getLog(HttpAccessUtil.class);

/**

* POST HTTP JSON请求

* @param url http://192.168.0.118/_Json/User/Login.ashx

* @param paramMap paramMap.put("token", userInfo);

* @return 没有error表示正确

*/

public static String httpPost(final String url, final Map paramMap) {

BasicNameValuePair[] paramArray = null;

if (paramMap != null) {

paramArray = new BasicNameValuePair[paramMap.size()];

int index = 0;

for (Map.Entry entry : paramMap.entrySet()) {

BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());

paramArray[index++] = pair;

}

}

return HttpClientManager.getInstance().httpPost(url, paramArray);

}

/**

* http get请求

* @param url

* @return

*/

public static String httpGet(final String url) {

return HttpClientManager.getInstance().httpGet(url);

}

/**

* https查询

* @param url 请求url

* @param paramMap 请求参数

* @return 查询结果

*/

public static String httpsPost(final String url, final Map paramMap){

String result=HttpsClientUtil.getInstance().doPost(url, paramMap,"utf-8");

if(LOG.isInfoEnabled()){

LOG.info("httpsPost查询结果:"+result);

}

return result;

}

/**

* https GET请求

* @param url 请求url

* @return 请求结果集

*/

public static String httpsGet(final String url){

String result = HttpsClientUtil.getInstance().doGet(url,"utf-8");

if(LOG.isInfoEnabled()){

LOG.info("httpsGet查询结果:"+result);

}

return result;

}

/**

* POST,支持参数是List

* @param url http://10.51.111.101/webapp/restful/openApiController/pushMessage

* @param

Map paramMap = new HashMap();

paramMap.put("fromUserCode", "liupeifeng");

List toUserCodes = new ArrayList();

toUserCodes.add("mapengfei");

toUserCodes.add("lilinwei");

paramMap.put("toUserCodes", toUserCodes);

paramMap.put("pushMessage", "企业社区test");

* @return 没有error表示正确

*/

public static String httpPostByListParam(final String url, final Map paramMap) {

List paramArray = null;

if (paramMap != null) {

paramArray = new ArrayList();

for (Map.Entry entry : paramMap.entrySet()) {

if (entry.getValue() != null && entry.getValue()instanceof List) {

@SuppressWarnings("unchecked")

List values = (List) entry.getValue();

for (String value : values) {

BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), value);

paramArray.add(pair);

}

} else {

BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));

paramArray.add(pair);

}

}

}

BasicNameValuePair [] nvp = null;

if (paramArray!=null) {

nvp = new BasicNameValuePair[paramArray.size()];

return HttpClientManager.getInstance().httpPost(url, paramArray.toArray(nvp));

}

return null;

}

public static void main(final String[] args) {

Map resultMap = new HashMap();

try {

// 需要加密的时间戳字串

String cSrc = String.valueOf(new Date().getTime());

// 加密

String userNameString = EHomeEncryptionUtil.generateToken("mapengfei@ygsoft.com");

String passWordString = EHomeEncryptionUtil.generateToken("4444.qqqq");

String dateString = EHomeEncryptionUtil.generateToken(cSrc);

String userInfo = userNameString+"@"+passWordString+"@"+dateString;

Map paramMap = new HashMap();

paramMap.put("token", userInfo);

//String result = HttpAccessUtil.httpPost("http://192.168.0.118/_Json/User/Login.ashx", paramMap);

String result = HttpAccessUtil.httpsPost("https://view.ygsoft.com/_Json/User/Login.ashx", paramMap);

if(result.indexOf("error") == -1){

resultMap.put("result", "1");

System.out.println(result);

}else{

System.out.println(result);

System.out.println("登录失败");

}

} catch (Exception e) {

e.printStackTrace();

}

}

/*public static void main(final String[] args) throws UnsupportedEncodingException {

Map paramMap = new HashMap();

paramMap.put("fromUserCode", "liupeifeng");

List toUserCodes = new ArrayList();

toUserCodes.add("mapengfei");

toUserCodes.add("lilinwei");

paramMap.put("toUserCodes", toUserCodes);

paramMap.put("pushMessage", "企业社区test");

String result = HttpAccessUtil.httpGet("http://10.51.111.101/webapp/restful/openApiController/sendMessage?fromUserCode=liupeifeng&toUserCodes=mapengfei&messageType=0&sendMessage=" + URLEncoder.encode("欢迎使用 API Store!!", "UTF-8"));

System.out.println(result);

String result1 = HttpAccessUtil.httpPostByListParam("http://ecp.ygsoft.com:9080/grm/ecp/app/services/automationCommonService", paramMap);

System.out.println(result1);

//http://10.52.1.35:9080/grm/ecp/app/services/automationCommonService

}*/

}

/********************************EHomeEncryptionUtil************/

/*

* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.

*/

package com.ygsoft.ecp.app.mappextend.impl.util;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

import com.ygsoft.ecp.service.log.EcpLogFactory;

import com.ygsoft.ecp.service.log.IEcpLog;

/**

* eHome加密类.

* 在JDK1.5下,避免key太长报错,必须更新jdk1.5.0_22\jre\lib\security的local_policy.jar,US_export_policy.jar

* @author liupeifeng

* @version 1.0.0 2014-12-9

* @see

* @since JDK 1.5.0

*/

public class EHomeEncryptionUtil {

/**

* EHomeEncryptionUtil.

*/

private static EHomeEncryptionUtil instance = new EHomeEncryptionUtil();

/**

* 日志.

*/

private static final IEcpLog LOG = EcpLogFactory.getLog(EHomeEncryptionUtil.class);

/**

* 私有构造函数.

*/

private EHomeEncryptionUtil() {

// 防止被new

}

/**

* 获取实例.

* @return 返回EHomeEncryptionUtil实例

*/

public static EHomeEncryptionUtil getInstance() {

return instance;

}

/**

* 生成令牌.

* @param ***c 源字符串

* @return 令牌

* @throws Exception 异常

*/

public static String generateToken(final String ***c) throws Exception {

final String sKey = "fcuu41vkq27zmp0w9gs06we3xohylm5u";//old

//    final String sKey = "69548545474684749858072123451255";//old

//        String sKey = getEcpPropertyQueryContext().getValue("auth_key");

// 需要加密两次

String token = encrypt(***c, sKey);

token = encrypt(token, sKey);

return token;

}

/**

* 加密

* @param ***c 待加密字符串

* @param sKey 密钥

* @return 已加密的字符串

* @throws Exception 异常

*/

private static String encrypt(final String ***c, final String sKey) throws Exception {

byte[] byteSrc = sKey.getBytes("utf-8");

SecretKeySpec skeySpec = new SecretKeySpec(byteSrc, "AES");

// "算法/模式/补码方式"

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal(***c.getBytes("utf-8"));

// 此处使用BASE64做转码功能,同时能起到2次加密的作用

return new String(new YBBase64().encode(encrypted),"utf-8");

//return new Base64().encode(encrypted).toString();

}

/**

* e家用户密码校验.

* @param username yhmc明文

* @param password yh密码明文

* @return 成功会返回邮箱,失败会返回error的字符串

*/

public static String validate(final String username, final String password) {

String result = "";

try {

// 需要加密的时间戳字串

String cSrc = String.valueOf(new Date().getTime());

// 加密

String userNameString = EHomeEncryptionUtil.generateToken(username);

String passWordString = EHomeEncryptionUtil.generateToken(password);

String dateString = EHomeEncryptionUtil.generateToken(cSrc);

String userInfo = userNameString+"@"+passWordString+"@"+dateString;

Map paramMap = new HashMap();

paramMap.put("token", userInfo);

result = HttpAccessUtil.httpsPost("https://view.ygsoft.com/_Json/User/Login.ashx", paramMap);

} catch (Exception e) {

LOG.error(e);

}

return result;

}

}

/*******************************************HttpClientManager************/

/*

* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.

*/

package com.ygsoft.ecp.app.mappextend.impl.util;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.InetAddress;

import java.net.URLDecoder;

import java.net.UnknownHostException;

import java.nio.charset.CodingErrorAction;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.Consts;

import org.apache.http.Header;

import org.apache.http.HttpRequest;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.ParseException;

import org.apache.http.client.ClientProtocolException;

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.ConnectionConfig;

import org.apache.http.config.MessageConstraints;

import org.apache.http.config.Registry;

import org.apache.http.config.RegistryBuilder;

import org.apache.http.config.SocketConfig;

import org.apache.http.conn.ConnectionKeepAliveStrategy;

import org.apache.http.conn.DnsResolver;

import org.apache.http.conn.HttpConnectionFactory;

import org.apache.http.conn.ManagedHttpClientConnection;

import org.apache.http.conn.routing.HttpRoute;

import org.apache.http.conn.socket.ConnectionSocketFactory;

import org.apache.http.conn.socket.PlainConnectionSocketFactory;

import org.apache.http.impl.DefaultHttpResponseFactory;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.impl.conn.DefaultHttpResponseParser;

import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;

import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import org.apache.http.impl.conn.SystemDefaultDnsResolver;

import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;

import org.apache.http.io.HttpMessageParser;

import org.apache.http.io.HttpMessageParserFactory;

import org.apache.http.io.HttpMessageWriterFactory;

import org.apache.http.io.SessionInputBuffer;

import org.apache.http.message.BasicHeader;

import org.apache.http.message.BasicLineParser;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.message.LineParser;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.CharArrayBuffer;

import org.apache.http.util.EntityUtils;

/**

* HttpClientManager.

* @author mapengfei

* @version 1.0.0 2014-12-10

* @see

* @since JDK 1.5.0

*/

public class HttpClientManager {

private static HttpClientManager instance = new HttpClientManager();

private PoolingHttpClientConnectionManager connManager = null;

private CloseableHttpClient httpclient = null;

private HttpClientManager() {

init();

}

public static HttpClientManager getInstance() {

return instance;

}

private void init() {

// Use custom message parser / writer to customize the way HTTP

// messages are parsed from and written out to the data stream.

HttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() {

@Override

public HttpMessageParser create(

final SessionInputBuffer buffer, final MessageConstraints constraints) {

LineParser lineParser = new BasicLineParser() {

@Override

public Header parseHeader(final CharArrayBuffer buffer) {

try {

return super.parseHeader(buffer);

} catch (ParseException ex) {

return new BasicHeader(buffer.toString(), null);

}

}

};

return new DefaultHttpResponseParser(

buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {

@Override

protected boolean reject(final CharArrayBuffer line, final int count) {

// try to ignore all garbage preceding a status line infinitely

return false;

}

};

}

};

HttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory();

// Use a custom connection factory to customize the process of

// initialization of outgoing HTTP connections. Beside standard connection

// configuration parameters HTTP connection factory can define message

// parser / writer routines to be employed by individual connections.

HttpConnectionFactory connFactory = new ManagedHttpClientConnectionFactory(

requestWriterFactory, responseParserFactory);

// Create a registry of custom connection socket factories for supported

// protocol schemes.

Registry socketFactoryRegistry = RegistryBuilder.create()

.register("http", PlainConnectionSocketFactory.INSTANCE)

.build();

// Use custom DNS resolver to override the system DNS resolution.

DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

@Override

public InetAddress[] resolve(final String host) throws UnknownHostException {

if (host.equalsIgnoreCase("myhost")) {

return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };

} else {

return super.resolve(host);

}

}

};

// Create a connection manager with custom configuration.

connManager = new PoolingHttpClientConnectionManager(

socketFactoryRegistry, connFactory, dnsResolver);

// Create socket configuration

SocketConfig socketConfig = SocketConfig.custom()

.setTcpNoDelay(true)

.build();

// Configure the connection manager to use socket configuration either

// by default or for a specific host.

connManager.setDefaultSocketConfig(socketConfig);

//connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

// Create message constraints

MessageConstraints messageConstraints = MessageConstraints.custom()

.setMaxHeaderCount(200)

.setMaxLineLength(2000)

.build();

// Create connection configuration

ConnectionConfig connectionConfig = ConnectionConfig.custom()

.setMalformedInputAction(CodingErrorAction.IGNORE)

.setUnmappableInputAction(CodingErrorAction.IGNORE)

.setCharset(Consts.UTF_8)

.setMessageConstraints(messageConstraints)

.build();

// Configure the connection manager to use connection configuration either

// by default or for a specific host.

connManager.setDefaultConnectionConfig(connectionConfig);

//connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

// Configure total max or per route limits for persistent connections

// that can be kept in the pool or leased by the connection manager.

connManager.setMaxTotal(600);

connManager.setDefaultMaxPerRoute(100);

//connManager.setMaxPerRoute(new HttpRoute(new HttpHost("10.52.10.240", 18080)), 100);

ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {

@Override

public long getKeepAliveDuration(

final HttpResponse response,

final HttpContext context) {

long keepAlive = super.getKeepAliveDuration(response, context);

if (keepAlive == -1) {

// Keep connections alive 5 seconds if a keep-alive value

// has not be explicitly set by the server

keepAlive = 5000;

}

return keepAlive;

}

};

// Create an HttpClient with the given custom dependencies and configuration.

httpclient = HttpClients.custom()

.setConnectionManager(connManager)

.setKeepAliveStrategy(keepAliveStrat)

.build();

}

/**

* http get请求.

* @param url 中文必须经过encode

* @return 结果,由请求的服务决定

*/

public String httpGet(final String url) {

CloseableHttpResponse response = null;

try {

HttpGet httpGet = new HttpGet(url);

response = httpclient.execute(httpGet);

String result = null;

if (response.getEntity() != null) {

result = EntityUtils.toString(response.getEntity());

result = URLDecoder.decode(result, "UTF-8");

}

return result;

} catch (UnsupportedEncodingException e1) {

} catch (ClientProtocolException e1) {

} catch (IOException e1) {

} finally {

try {

if (response != null) {

response.close();

}

} catch (IOException e) {

}

}

return null;

}

/**

* POST HTTP JSON请求.

* @author chenxiangbai 2012-12-6 下午4:52:43

* @param url post的URL,例如:http://10.52.2.1:8080/Resteasy/ResteasyService/postTestInfo

* @param param post参数的键值对.

* @return HttpResponse.

*/

public String httpPost(final String url, final BasicNameValuePair... param) {

HttpPost httpPost = new HttpPost(url);

List nvps = new ArrayList ();

if (param != null) {

for (BasicNameValuePair nameValuePair : param) {

nvps.add(nameValuePair);

}

}

CloseableHttpResponse response = null;

try {

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

response = httpclient.execute(httpPost);

String result = null;

if (response.getEntity() != null) {

result = EntityUtils.toString(response.getEntity());

result = URLDecoder.decode(result, "UTF-8");

}

return result;

} catch (UnsupportedEncodingException e1) {

} catch (ClientProtocolException e1) {

} catch (IOException e1) {

} finally {

try {

if (response != null) {

response.close();

}

} catch (IOException e) {

}

}

return null;

}

}

/**************************************8HttpsClientUtil***********************/

/*

* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.

*/

package com.ygsoft.ecp.app.mappextend.impl.util;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

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.impl.client.CloseableHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import com.ygsoft.ecp.service.log.EcpLogFactory;

import com.ygsoft.ecp.service.log.IEcpLog;

/**

* TODO 在此写上类的相关说明.

* @author mapengfei

* @version 1.0.0 2016年5月16日

* @see

* @since JDK 1.5.0

*/

public class HttpsClientUtil {

/**

* 日志

*/

private static final IEcpLog LOG = EcpLogFactory.getLog(HttpsClientUtil.class);

/**

* httpclient链接

*/

private CloseableHttpClient httpClient = null;

private static HttpsClientUtil instance = new HttpsClientUtil();

public static HttpsClientUtil getInstance() {

return instance;

}

/**

* post请求

* @param url 服务请求url

* @param map 参数

* @param charset 编码

* @return 请求结果json

*/

@SuppressWarnings({"unchecked", "rawtypes" })

public String doPost(final String url,final Map map,final String charset){

HttpPost httpPost = null;

CloseableHttpResponse response=null;

String result = null;

try{

httpClient = new SSLClient();

httpPost = new HttpPost(url);

//设置参数

List list = new ArrayList();

Iterator iterator = map.entrySet().iterator();

while(iterator.hasNext()){

Entry elem = (Entry) iterator.next();

list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));

}

if(list.size() > 0){

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);

httpPost.setEntity(entity);

}

response = httpClient.execute(httpPost);

if(response != null){

HttpEntity resEntity = response.getEntity();

if(resEntity != null){

result = EntityUtils.toString(resEntity,charset);

}

}

}catch(Exception ex){

ex.printStackTrace();

}finally {

try {

if (response != null) {

response.close();

}

} catch (IOException e) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doPost的response有IOException关闭异常异常:"+e.getMessage());

}

}

}

return result;

}

/**

* doGet请求

* @param url 请求地址

* @param map 参数map

* @param charset 编码

* @return 查询结果

*/

public String doGet(final String url,final String charset){

CloseableHttpResponse response = null;

try {

httpClient = new SSLClient();

HttpGet httpGet = new HttpGet(url);

response = httpClient.execute(httpGet);

String result = null;

if (response.getEntity() != null) {

result = EntityUtils.toString(response.getEntity());

result = URLDecoder.decode(result,charset);

}

return result;

} catch (UnsupportedEncodingException e1) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doGet有UnsupportedEncodingException异常:"+e1.getMessage());

}

} catch (ClientProtocolException e1) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doGet有ClientProtocolException异常:"+e1.getMessage());

}

} catch (IOException e1) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doGet有IOException异常:"+e1.getMessage());

}

} catch (Exception e) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doGet有IOException异常:"+e.getMessage());

}

e.printStackTrace();

} finally {

try {

if (response != null) {

response.close();

}

} catch (IOException e) {

if(LOG.isInfoEnabled()){

LOG.info("HttpsClientUtil.doGet的response有IOException关闭异常异常:"+e.getMessage());

}

}

}

return null;

}

}

/***********************************888DefaultHttpClient*****************/

/*

* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.

*/

package com.ygsoft.ecp.app.mappextend.impl.util;

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;

/**

* TODO 在此写上类的相关说明.

* @author mapengfei

* @version 1.0.0 2016年5月16日

* @see

* @since JDK 1.5.0

*/

@SuppressWarnings("deprecation")

public class SSLClient extends DefaultHttpClient{

public SSLClient() throws Exception{

super();

SSLContext ctx = SSLContext.getInstance("TLS");

X509TrustManager tm = new X509TrustManager() {

public void checkClientTrusted(final X509Certificate[] chain,

final String authType) throws CertificateException {

}

public void checkServerTrusted(final X509Certificate[] chain,

final String authType) throws CertificateException {

}

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));

}

}

/**********************************8YBBase64****************************/

package com.ygsoft.ecp.app.mappextend.impl.util;

import java.math.BigInteger;

/**

* ehome用的是commons-codec-1.4.jar,只能在这里迁移一份.

* ecp目前使用的是1.3版本,如果直接用Base64处理将会出现编码后不一致.

* @author mapengfei

* @version 1.0.0 2014-12-9

* @see

* @since JDK 1.5.0

*/

public class YBBase64 {

public YBBase64()

{

this(false);

}

public YBBase64(final boolean urlSafe)

{

this(76, CHUNK_SEPARATOR, urlSafe);

}

public YBBase64(final int lineLength)

{

this(lineLength, CHUNK_SEPARATOR);

}

public YBBase64(final int lineLength, final byte lineSeparator[])

{

this(lineLength, lineSeparator, false);

}

public YBBase64(int lineLength, byte lineSeparator[], final boolean urlSafe)

{

if(lineSeparator == null)

{

lineLength = 0;

lineSeparator = CHUNK_SEPARATOR;

}

this.lineLength = lineLength <= 0 ? 0 : (lineLength / 4) * 4;

this.lineSeparator = new byte[lineSeparator.length];

System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);

if(lineLength > 0)

encodeSize = 4 + lineSeparator.length;

else

encodeSize = 4;

decodeSize = encodeSize - 1;

if(containsBase64Byte(lineSeparator))

{

String sep = StringUtils.newStringUtf8(lineSeparator);

throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]");

} else

{

encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;

return;

}

}

public boolean isUrlSafe()

{

return encodeTable == URL_SAFE_ENCODE_TABLE;

}

/*boolean hasData()

{

return buffer != null;

}*/

int avail()

{

return buffer == null ? 0 : pos - readPos;

}

private void resizeBuffer()

{

if(buffer == null)

{

buffer = new byte[8192];

pos = 0;

readPos = 0;

} else

{

byte b[] = new byte[buffer.length * 2];

System.arraycopy(buffer, 0, b, 0, buffer.length);

buffer = b;

}

}

int readResults(final byte b[], final int bPos, final int bAvail)

{

if(buffer != null)

{

int len = Math.min(avail(), bAvail);

if(buffer != b)

{

System.arraycopy(buffer, readPos, b, bPos, len);

readPos += len;

if(readPos >= pos)

buffer = null;

} else

{

buffer = null;

}

return len;

} else

{

return eof ? -1 : 0;

}

}

void setInitialBuffer(final byte out[], final int outPos, final int outAvail)

{

if(out != null && out.length == outAvail)

{

buffer = out;

pos = outPos;

readPos = outPos;

}

}

void encode(final byte in[], int inPos, final int inAvail)

{

if(eof)

return;

if(inAvail < 0)

{

eof = true;

if(buffer == null || buffer.length - pos < encodeSize)

resizeBuffer();

switch(modulus)

{

case 1: // '\001'

buffer[pos++] = encodeTable[x >> 2 & 63];

buffer[pos++] = encodeTable[x << 4 & 63];

if(encodeTable == STANDARD_ENCODE_TABLE)

{

buffer[pos++] = 61;

buffer[pos++] = 61;

}

break;

case 2: // '\002'

buffer[pos++] = encodeTable[x >> 10 & 63];

buffer[pos++] = encodeTable[x >> 4 & 63];

buffer[pos++] = encodeTable[x << 2 & 63];

if(encodeTable == STANDARD_ENCODE_TABLE)

buffer[pos++] = 61;

break;

}

if(lineLength > 0 && pos > 0)

{

System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);

pos += lineSeparator.length;

}

} else

{

for(int i = 0; i < inAvail; i++)

{

if(buffer == null || buffer.length - pos < encodeSize)

resizeBuffer();

modulus = ++modulus % 3;

int b = in[inPos++];

if(b < 0)

b += 256;

x = (x << 8) + b;

if(0 != modulus)

continue;

buffer[pos++] = encodeTable[x >> 18 & 63];

buffer[pos++] = encodeTable[x >> 12 & 63];

buffer[pos++] = encodeTable[x >> 6 & 63];

buffer[pos++] = encodeTable[x & 63];

currentLinePos += 4;

if(lineLength > 0 && lineLength <= currentLinePos)

{

System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);

pos += lineSeparator.length;

currentLinePos = 0;

}

}

}

}

void decode(final byte in[], int inPos, final int inAvail)

{

if(eof)

return;

if(inAvail < 0)

eof = true;

for(int i = 0; i < inAvail; i++)

{

if(buffer == null || buffer.length - pos < decodeSize)

resizeBuffer();

byte b = in[inPos++];

if(b == 61)

{

eof = true;

break;

}

if(b < 0 || b >= DECODE_TABLE.length)

continue;

int result = DECODE_TABLE[b];

if(result < 0)

continue;

modulus = ++modulus % 4;

x = (x << 6) + result;

if(modulus == 0)

{

buffer[pos++] = (byte)(x >> 16 & 255);

buffer[pos++] = (byte)(x >> 8 & 255);

buffer[pos++] = (byte)(x & 255);

}

}

if(eof && modulus != 0)

{

x = x << 6;

switch(modulus)

{

case 2: // '\002'

x = x << 6;

buffer[pos++] = (byte)(x >> 16 & 255);

break;

case 3: // '\003'

buffer[pos++] = (byte)(x >> 16 & 255);

buffer[pos++] = (byte)(x >> 8 & 255);

break;

}

}

}

public static boolean isBase64(final byte octet)

{

return octet == 61 || octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1;

}

public static boolean isArrayByteBase64(final byte arrayOctet[])

{

for(int i = 0; i < arrayOctet.length; i++)

if(!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i]))

return false;

return true;

}

private static boolean containsBase64Byte(final byte arrayOctet[])

{

for(int i = 0; i < arrayOctet.length; i++)

if(isBase64(arrayOctet[i]))

return true;

return false;

}

public static byte[] encodeBase64(final byte binaryData[])

{

return encodeBase64(binaryData, false);

}

public static String encodeBase64String(final byte binaryData[])

{

return StringUtils.newStringUtf8(encodeBase64(binaryData, true));

}

public static byte[] encodeBase64URLSafe(final byte binaryData[])

{

return encodeBase64(binaryData, false, true);

}

public static String encodeBase64URLSafeString(final byte binaryData[])

{

return StringUtils.newStringUtf8(encodeBase64(binaryData, false, true));

}

public static byte[] encodeBase64Chunked(final byte binaryData[])

{

return encodeBase64(binaryData, true);

}

public Object decode(final Object pObject)

throws Exception

{

if(pObject instanceof byte[])

return decode((byte[])(byte[])pObject);

if(pObject instanceof String)

return decode((String)pObject);

else

throw new Exception("Parameter supplied to Base64 decode is not a byte[] or a String");

}

public byte[] decode(final String pArray)

{

return decode(StringUtils.getBytesUtf8(pArray));

}

public byte[] decode(final byte pArray[])

{

reset();

if(pArray == null || pArray.length == 0)

{

return pArray;

} else

{

long len = (pArray.length * 3) / 4;

byte buf[] = new byte[(int)len];

setInitialBuffer(buf, 0, buf.length);

decode(pArray, 0, pArray.length);

decode(pArray, 0, -1);

byte result[] = new byte[pos];

readResults(result, 0, result.length);

return result;

}

}

public static byte[] encodeBase64(final byte binaryData[], final boolean isChunked)

{

return encodeBase64(binaryData, isChunked, false);

}

public static byte[] encodeBase64(final byte binaryData[], final boolean isChunked, final boolean urlSafe)

{

return encodeBase64(binaryData, isChunked, urlSafe, 2147483647);

}

public static byte[] encodeBase64(final byte binaryData[], final boolean isChunked, final boolean urlSafe, final int maxResultSize)

{

if(binaryData == null || binaryData.length == 0)

return binaryData;

long len = getEncodeLength(binaryData, 76, CHUNK_SEPARATOR);

if(len > (long)maxResultSize)

{

throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len + ") than the specified maxium size of " + maxResultSize);

} else

{

YBBase64 b64 = isChunked ? new YBBase64(urlSafe) : new YBBase64(0, CHUNK_SEPARATOR, urlSafe);

return b64.encode(binaryData);

}

}

public static byte[] decodeBase64(final String base64String)

{

return (new YBBase64()).decode(base64String);

}

public static byte[] decodeBase64(final byte base64Data[])

{

return (new YBBase64()).decode(base64Data);

}

/**

* @deprecated Method discardWhitespace is deprecated

*/

static byte[] discardWhitespace(final byte data[])

{

byte groomedData[] = new byte[data.length];

int bytesCopied = 0;

int i = 0;

do

if(i < data.length)

{

switch(data[i])

{

default:

groomedData[bytesCopied++] = data[i];

// fall through

case 9: // '\t'

case 10: // '\n'

case 13: // '\r'

case 32: // ' '

i++;

break;

}

} else

{

byte packedData[] = new byte[bytesCopied];

System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);

return packedData;

}

while(true);

}

private static boolean isWhiteSpace(final byte byteToCheck)

{

switch(byteToCheck)

{

case 9: // '\t'

case 10: // '\n'

case 13: // '\r'

case 32: // ' '

return true;

}

return false;

}

public Object encode(final Object pObject)

throws Exception

{

if(!(pObject instanceof byte[]))

throw new Exception("Parameter supplied to Base64 encode is not a byte[]");

else

return encode((byte[])(byte[])pObject);

}

public String encodeToString(final byte pArray[])

{

return StringUtils.newStringUtf8(encode(pArray));

}

public byte[] encode(final byte pArray[])

{

reset();

if(pArray == null || pArray.length == 0)

return pArray;

long len = getEncodeLength(pArray, lineLength, lineSeparator);

byte buf[] = new byte[(int)len];

setInitialBuffer(buf, 0, buf.length);

encode(pArray, 0, pArray.length);

encode(pArray, 0, -1);

if(buffer != buf)

readResults(buf, 0, buf.length);

if(isUrlSafe() && pos < buf.length)

{

byte smallerBuf[] = new byte[pos];

System.arraycopy(buf, 0, smallerBuf, 0, pos);

buf = smallerBuf;

}

return buf;

}

private static long getEncodeLength(final byte pArray[], int chunkSize, final byte chunkSeparator[])

{

chunkSize = (chunkSize / 4) * 4;

long len = (pArray.length * 4) / 3;

long mod = len % 4L;

if(mod != 0L)

len += 4L - mod;

if(chunkSize > 0)

{

boolean lenChunksPerfectly = len % (long)chunkSize == 0L;

len += (len / (long)chunkSize) * (long)chunkSeparator.length;

if(!lenChunksPerfectly)

len += chunkSeparator.length;

}

return len;

}

public static BigInteger decodeInteger(final byte pArray[])

{

return new BigInteger(1, decodeBase64(pArray));

}

public static byte[] encodeInteger(final BigInteger bigInt)

{

if(bigInt == null)

throw new NullPointerException("encodeInteger called with null parameter");

else

return encodeBase64(toIntegerBytes(bigInt), false);

}

static byte[] toIntegerBytes(final BigInteger bigInt)

{

int bitlen = bigInt.bitLength();

bitlen = (bitlen + 7 >> 3) << 3;

byte bigBytes[] = bigInt.toByteArray();

if(bigInt.bitLength() % 8 != 0 && bigInt.bitLength() / 8 + 1 == bitlen / 8)

return bigBytes;

int startSrc = 0;

int len = bigBytes.length;

if(bigInt.bitLength() % 8 == 0)

{

startSrc = 1;

len--;

}

int startDst = bitlen / 8 - len;

byte resizedBytes[] = new byte[bitlen / 8];

System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);

return resizedBytes;

}

private void reset()

{

buffer = null;

pos = 0;

readPos = 0;

currentLinePos = 0;

modulus = 0;

eof = false;

}

@SuppressWarnings("unused")

private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;

@SuppressWarnings("unused")

private static final int DEFAULT_BUFFER_SIZE = 8192;

static final int CHUNK_SIZE = 76;

static final byte CHUNK_SEPARATOR[] = {

13, 10

};

private static final byte STANDARD_ENCODE_TABLE[] = {

65, 66, 67, 68, 69, 70, 71, 72, 73, 74,

75, 76, 77, 78, 79, 80, 81, 82, 83, 84,

85, 86, 87, 88, 89, 90, 97, 98, 99, 100,

101, 102, 103, 104, 105, 106, 107, 108, 109, 110,

111, 112, 113, 114, 115, 116, 117, 118, 119, 120,

121, 122, 48, 49, 50, 51, 52, 53, 54, 55,

56, 57, 43, 47

};

private static final byte URL_SAFE_ENCODE_TABLE[] = {

65, 66, 67, 68, 69, 70, 71, 72, 73, 74,

75, 76, 77, 78, 79, 80, 81, 82, 83, 84,

85, 86, 87, 88, 89, 90, 97, 98, 99, 100,

101, 102, 103, 104, 105, 106, 107, 108, 109, 110,

111, 112, 113, 114, 115, 116, 117, 118, 119, 120,

121, 122, 48, 49, 50, 51, 52, 53, 54, 55,

56, 57, 45, 95

};

@SuppressWarnings("unused")

private static final byte PAD = 61;

private static final byte DECODE_TABLE[] = {

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, 62, -1, 62, -1, 63, 52, 53,

54, 55, 56, 57, 58, 59, 60, 61, -1, -1,

-1, -1, -1, -1, -1, 0, 1, 2, 3, 4,

5, 6, 7, 8, 9, 10, 11, 12, 13, 14,

15, 16, 17, 18, 19, 20, 21, 22, 23, 24,

25, -1, -1, -1, -1, 63, -1, 26, 27, 28,

29, 30, 31, 32, 33, 34, 35, 36, 37, 38,

39, 40, 41, 42, 43, 44, 45, 46, 47, 48,

49, 50, 51

};

@SuppressWarnings("unused")

private static final int MASK_6BITS = 63;

@SuppressWarnings("unused")

private static final int MASK_8BITS = 255;

private final byte encodeTable[];

private final int lineLength;

private final byte lineSeparator[];

private final int decodeSize;

private final int encodeSize;

private byte buffer[];

private int pos;

private int readPos;

private int currentLinePos;

private int modulus;

private boolean eof;

private int x;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值