您的位置:首页 > 编程语言 > Java开发

JavaMail接收邮件,并解析邮件(用于解决一些线上问题)

2015-06-29 22:49 561 查看
JavaMail相关必须包

1、接收邮件解析邮件

package com.xxxx.error.process;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class ReciveMail {
private MimeMessage mimeMessage = null;
private String saveAttachPath = ""; // 附件下载后的存放目录
private StringBuffer bodytext = new StringBuffer();// 存放邮件内容
private String dateformat = "yy-MM-dd HH:mm"; // 默认的日前显示格式

public ReciveMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

public void setMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

/**
* 获得发件人的地址和姓名
*/
public String getFrom() throws Exception {
InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
String from = address[0].getAddress();
if (from == null)
from = "";
String personal = address[0].getPersonal();
if (personal == null)
personal = "";
String fromaddr = personal + "<" + from + ">";
return fromaddr;
}

/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
public String getMailAddress(String type) throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email);
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal + "<" + email + ">";
mailaddr += "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}

/**
* 获得邮件主题
*/
public String getSubject() throws MessagingException {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {
}
return subject;
}

/**
* 获得邮件发送日期
*/
public String getSentDate() throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}

/**
* 获得邮件正文内容
*/
public String getBodyText() {
return bodytext.toString();
}

/**
* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
*/
public void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
System.out.println("CONTENTTYPE: " + contenttype);
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
} else {
}
}

/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*/
public boolean getReplySign() throws MessagingException {
boolean replysign = false;
String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}

/**
* 获得此邮件的Message-ID
*/
public String getMessageId() throws MessagingException {
return mimeMessage.getMessageID();
}

/**
* 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
*/
public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = ((Message) mimeMessage).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
System.out.println("flags's length: " + flag.length);
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
System.out.println("seen Message  .");
break;
}
}
return isnew;
}

/**
* 判断此邮件是否包含附件
*/
public boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false;
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
attachflag = true;
else if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach((Part) mpart);
} else {
String contype = mpart.getContentType();
if (contype.toLowerCase().indexOf("application") != -1)
attachflag = true;
if (contype.toLowerCase().indexOf("name") != -1)
attachflag = true;
}
}
} else if (part.isMimeType("message/rfc822")) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}

/**
* 【保存附件】
*/
public void saveAttachMent(Part part) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
}

/**
* 【设置附件存放路径】
*/
public void setAttachPath(String attachpath) {
this.saveAttachPath = attachpath;
}

/**
* 【设置日期显示格式】
*/
public void setDateFormat(String format) throws Exception {
this.dateformat = format;
}

/**
* 【获得附件存放路径】
*/
public String getAttachPath() {
return saveAttachPath;
}

/**
* 【真正的保存附件到指定目录里】
*/
private void saveFile(String fileName, InputStream in) throws Exception {
String osName = System.getProperty("os.name");
String storedir = getAttachPath();
String separator = "";
if (osName == null)
osName = "";
if (osName.toLowerCase().indexOf("win") != -1) {
separator = "\\";
if (storedir == null || storedir.equals(""))
storedir = "c:\\tmp";
} else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator + fileName);
System.out.println("storefile's path: " + storefile.toString());

BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失败!");
} finally {
bos.close();
bis.close();
}
}

private static void excuteErrorRequest(String msgContent) {
String msgBodyText = msgContent.trim();
String paramter = msgBodyText.substring(msgBodyText.indexOf("<h4>参数:</h4>")+12, msgBodyText.indexOf("<br/>"));
System.out.println("--->> 请求发起....");
String result = sendHttpRequest(paramter);
System.out.println("--->> 返回结果:" + result);
}

private static String sendHttpRequest(String paramter) {
String url = "http://xxx.xxxxx.com/api/router/rest.do?" + paramter;
System.out.println("--->> " + url);
return HttpsUtil.requestGet(url);
}

/**
* PraseMimeMessage类测试
*/
public static void main(String args[]) throws Exception {

Properties props = System.getProperties();
props.put("mail.smtp.host", "mail.lvmama.com");
props.put("mail.smtp.auth", "false");
Session session = Session.getDefaultInstance(props, null);
URLName urln = new URLName("pop3", "mail.lvmama.com", 110, null, "xxxxxx@xx.com", "mima");
Store store = session.getStore(urln);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();
System.out.println("您有邮件: " + message.length + "封");
System.out.println("Ary you ready?");
Thread.sleep(1000);
System.out.println("3");
Thread.sleep(1000);
System.out.println("2");
Thread.sleep(1000);
System.out.println("1");
Thread.sleep(1000);
System.out.println("GO>>>>>");
ReciveMail pmm = null;
for (int i = 0; i < message.length; i++) {
System.out.println("==============================第" + (i + 1) + "封===========================");
pmm = new ReciveMail((MimeMessage) message[i]);
System.out.println("subject: " + pmm.getSubject());
System.out.println("sentdate: " + pmm.getSentDate());
System.out.println("replysign: " + pmm.getReplySign());
System.out.println("hasRead: " + pmm.isNew());
System.out.println("containAttachment: " + pmm.isContainAttach((Part) message[i]));
System.out.println("form: " + pmm.getFrom());
System.out.println("to: " + pmm.getMailAddress("to"));
System.out.println("cc: " + pmm.getMailAddress("cc"));
System.out.println("bcc: " + pmm.getMailAddress("bcc"));
pmm.setDateFormat("yy年MM月dd日 HH:mm");
System.out.println("send date: " + pmm.getSentDate());
System.out.println("Message " + i + " Message-ID: " + pmm.getMessageId());
// 获得邮件内容===============
pmm.getMailContent((Part) message[i]);
System.out.println("Message " + i + " bodycontent: \r\n" + pmm.getBodyText());
if("<cmswarn@lvmama.com>".equals(pmm.getFrom().trim())) {
String msgBodyText = pmm.getBodyText();
excuteErrorRequest(msgBodyText);
}
pmm.setAttachPath("c:\\ddd");
pmm.saveAttachMent((Part) message[i]);
}
}
}


2、发送HTTP请求工具

package com.xxxx.error.process;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpsUtil {
private static final Log LOG = LogFactory.getLog(HttpsUtil.class);

public static final String CHARACTER_ENCODING = "UTF-8";
public static final String PATH_SIGN = "/";
public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET";
public static final String CONTENT_TYPE = "Content-Type";

public static final int CONNECTION_TIMEOUT = 10000;
public static final int SO_TIMEOUT = 30000;
public static final int SO_TIMEOUT_60S = 60000;

public static final int BUFFER = 1024;

/**
* HttpResponse包装类
*/
public static class HttpResponseWrapper {
private HttpResponse httpResponse;
private HttpClient httpClient;

public HttpResponseWrapper(HttpClient httpClient, HttpResponse httpResponse) {
this.httpClient = httpClient;
this.httpResponse = httpResponse;
}

public HttpResponseWrapper(HttpClient httpClient) {
this.httpClient = httpClient;
}
public HttpResponse getHttpResponse() {
return httpResponse;
}
public void setHttpResponse(HttpResponse httpResponse) {
this.httpResponse = httpResponse;
}

/**
* 获得流类型的响应
*/
public InputStream getResponseStream() throws IllegalStateException, IOException {
return httpResponse.getEntity().getContent();
}

/**
* 获得字符串类型的响应
*/
public String getResponseString(String responseCharacter) throws ParseException, IOException {
HttpEntity entity = getEntity();
String responseStr = EntityUtils.toString(entity, responseCharacter);
if (entity.getContentType() == null) {
responseStr = new String(responseStr.getBytes("iso-8859-1"), responseCharacter);
}
EntityUtils.consume(entity);
return responseStr;
}

public String getResponseString() throws ParseException, IOException {
return getResponseString(CHARACTER_ENCODING);
}

/**
* 获得响应状态码
*/
public int getStatusCode() {
return httpResponse.getStatusLine().getStatusCode();
}

/**
* 获得响应状态码并释放资源
*/
public int getStatusCodeAndClose() {
close();
return getStatusCode();
}

public HttpEntity getEntity() {
return httpResponse.getEntity();
}

/**
* 释放资源
*/
public void close() {
httpClient.getConnectionManager().shutdown();
}
}

/**
* POST方式提交上传文件请求
*/
public static HttpResponseWrapper requestPostUpload(String url, Map<String, File> requestFiles, Map<String, String> requestParas, String requestCharacter) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient();
}else{
client =createHttpClient();
}
HttpPost httpPost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(requestCharacter));
if (requestFiles == null || requestFiles.size() == 0) {
return null;
}
for (Map.Entry<String, File> entry : requestFiles.entrySet()) {
multipartEntity.addPart(entry.getKey(), new FileBody(entry.getValue(), "application/octet-stream", requestCharacter));
}
if (requestParas != null && requestParas.size() > 0) {
// 对key进行排序
List<String> keys = new ArrayList<String>(requestParas.keySet());
Collections.sort(keys);
for (String key : keys) {
multipartEntity.addPart(key, new StringBody(requestParas.get(key), Charset.forName(requestCharacter)));
}
}
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = client.execute(httpPost);
return new HttpResponseWrapper(client, httpResponse);
}
/**
* POST方式提交上传文件请求
*/
public static HttpResponseWrapper requestPostUpload(String url, Map<String, File> requestFiles, Map<String, String> requestParas) throws ClientProtocolException, IOException {
return requestPostUpload(url, requestFiles, requestParas, CHARACTER_ENCODING);
}
/**
* POST方式提交表单数据,返回响应对象
*/
public static HttpResponseWrapper requestPostFormResponse(String url, Map<String, String> requestParas, String requestCharacter) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient();
}else{
client =createHttpClient();
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formParams = initNameValuePair(requestParas);
httpPost.setEntity(new UrlEncodedFormEntity(formParams, requestCharacter));
HttpResponse httpResponse = client.execute(httpPost); //执行POST请求
return new HttpResponseWrapper(client, httpResponse);
}

/**
* 自定义操作表单提交的数据
* @return
*/
public static HttpResponseWrapper requestPostFormResponse2(String url, Map<String, String> requestParas,int timeOut)throws IOException, HttpException{
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient(CONNECTION_TIMEOUT,timeOut*1000);
}else{
client =createHttpClient(CONNECTION_TIMEOUT,timeOut*1000);
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formParams = initNameValuePair(requestParas);
httpPost.setEntity(new HttpParamEncodeEntity(formParams, CHARACTER_ENCODING));
HttpResponse httpResponse = client.execute(httpPost); //执行POST请求
return new HttpResponseWrapper(client, httpResponse);
}

/**
* POST方式提交表单数据,返回响应对象,utf8编码
*/
public static HttpResponseWrapper requestPostFormResponse(String url, Map<String, String> requestParas) throws ClientProtocolException, IOException {
return requestPostFormResponse(url, requestParas, CHARACTER_ENCODING);
}
/**
* POST方式提交表单数据,不会自动重定向
*/
public static String requestPostForm(String url, Map<String, String> requestParas, String requestCharacter, String responseCharacter) {
HttpResponseWrapper httpResponseWrapper = null;
try {
httpResponseWrapper = requestPostFormResponse(url, requestParas, requestCharacter);
return httpResponseWrapper.getResponseString(responseCharacter);
} catch (Exception e) {
LOG.error(e);
} finally {
httpResponseWrapper.close();
}
return null;

}
/**
* POST方式提交表单数据,不会自动重定向
*/
public static String requestPostForm(String url, Map<String, String> requestParas) {
return requestPostForm(url, requestParas, CHARACTER_ENCODING, CHARACTER_ENCODING);
}

public static HttpResponseWrapper requestGetResponse(String url) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient();
}else{
client =createHttpClient();
}
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = client.execute(httpGet);
return new HttpResponseWrapper(client, httpResponse);
}

public static HttpResponseWrapper requestGetResponse(String url,String xForWardedFor) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient();
}else{
client =createHttpClient();
}
HttpGet httpGet = new HttpGet(url);
if(StringUtils.isNotEmpty(xForWardedFor)){
httpGet.addHeader("X-Forwarded-For", xForWardedFor);
}
HttpResponse httpResponse = client.execute(httpGet);
return new HttpResponseWrapper(client, httpResponse);
}
/**
* GET方式提交URL请求,会自动重定向
*/
public static String requestGet(String url, String responseCharacter,String xForWardedFor) {
HttpResponseWrapper httpResponseWrapper = null;
try {
httpResponseWrapper = requestGetResponse(url,xForWardedFor);
return httpResponseWrapper.getResponseString(responseCharacter);
} catch (Exception e) {
LOG.error(e);
} finally {
if(httpResponseWrapper!=null){
httpResponseWrapper.close();
}
}
return null;
}

/**
* GET方式提交URL请求,会自动重定向
*/
public static String requestGet(String url) {
return requestGet(url, CHARACTER_ENCODING,null);
}

/**
* get请求
* @param url 请求url(eg:https://api.lvmama.com/user/getUserInfo)
* @param params 参数
* @return 响应信息
*/
public static String requestGet(String url,Map<String, Object> params) {
StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("?").append(mapToUrl(params));
return requestGet(urlBuilder.toString(), CHARACTER_ENCODING,null);
}

/**
* 将Map中的数据组装成url
* @param params
* @return
*/
public static String mapToUrl(Map<String, Object> params) {
StringBuilder sb = new StringBuilder();
try {
boolean isFirst = true;
for (String key : params.keySet()) {
String value = (String) params.get(key);
if (isFirst) {
sb.append(key + "=" + URLEncoder.encode(value, "utf-8"));
isFirst = false;
} else {
if (value != null) {
sb.append("&" + key + "="
+ URLEncoder.encode(value, "utf-8"));
} else {
sb.append("&" + key + "=");
}
}
}
} catch (Exception e) {
LOG.error(e);
}
return sb.toString();
}

/**
* GET方式提交URL请求,会自动重定向
*/
public static String proxyRequestGet(String url,String xForWardedFor) {
return requestGet(url, CHARACTER_ENCODING,xForWardedFor);
}

/**
* POST方式提交非表单数据,返回响应对象
*/
public static HttpResponseWrapper requestPostData(String url, String data, String contentType, String requestCharacter,int connectionTimeout,int soTimeout) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient(connectionTimeout,soTimeout);
}else{
client =createHttpClient(connectionTimeout,soTimeout);
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, requestCharacter));
HttpResponse httpResponse = client.execute(httpPost);
return new HttpResponseWrapper(client, httpResponse);
}

/**
* POST方式提交非表单数据,返回响应对象
*/
public static HttpResponseWrapper requestPostData(String url, String data, String contentType, String requestCharacter) throws ClientProtocolException, IOException {
return requestPostData(url,data,contentType,requestCharacter,CONNECTION_TIMEOUT,SO_TIMEOUT);
}
/**
* POST非表单方式提交XML数据
*/
public static String requestPostXml(String url, String xmlData, String requestCharacter, String responseCharacter) {
HttpResponseWrapper httpResponseWrapper = null;
try {
String contentType = "text/xml; charset=" + requestCharacter;
httpResponseWrapper = requestPostData(url, xmlData, contentType, requestCharacter);
return httpResponseWrapper.getResponseString(responseCharacter);
} catch (Exception e) {
LOG.error(e);
} finally {
httpResponseWrapper.close();
}
return null;
}
/**
* POST非表单方式提交XML数据
*/
public static String requestPostXml(String url, String xmlData) {
return requestPostXml(url, xmlData, CHARACTER_ENCODING, CHARACTER_ENCODING);
}

public static HttpClient createHttpClient(int connectionTimeout,int soTimeout) {
HttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
HttpConnectionParams.setSoTimeout(params, soTimeout);
return httpClient;
}

public static HttpClient createHttpClient() {
return createHttpClient(CONNECTION_TIMEOUT,SO_TIMEOUT);
}

public static HttpClient createHttpsClient(int connectionTimeout,int soTimeout)  {
try {
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
HttpConnectionParams.setSoTimeout(params, soTimeout);
//TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
//使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);
//创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
return httpClient;
} catch (Exception e) {
LOG.error(e);
}
return null;
}

public static HttpClient createHttpsClient()  {
return createHttpsClient(CONNECTION_TIMEOUT,SO_TIMEOUT);
}

public static List<NameValuePair> initNameValuePair(Map<String, String> params) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
// 对key进行排序
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
for (String key : keys) {
//LOG.info(key+" = " +params.get(key));
formParams.add(new BasicNameValuePair(key, params.get(key)));
}
}
return formParams;
}

/**
* 通过httpclient下载的文件直接转为字节数组
* @param path
* @return
*/
public static byte[] getHttpClientResponseByteArray(String path){
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
GetMethod httpGet = new GetMethod(path);

byte[] byteArrays = new byte[0];
try{
client.executeMethod(httpGet);
InputStream in = httpGet.getResponseBodyAsStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] b = new byte[BUFFER];
int len = 0;
while((len=in.read(b))!= -1){
bos.write(b, 0, len);
}
byteArrays =  bos.toByteArray();
in.close();
bos.close();
}catch (Exception e){
LOG.error(e);
}finally{
httpGet.releaseConnection();
}
return byteArrays;
}

private static class TrustAnyTrustManager implements X509TrustManager {

public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}

/******************** 已下为客户端新加  2014-05-29*****************/
/**
* 客户端调用
* POST方式提交表单数据,不会自动重定向
* @param url                 请求url
* @param requestParas        请求参数
* @param xForWardedFor       请求ip(统计客户端登陆次数)
*
*/
public static String requestPostForm(String url, Map<String, String> requestParas,String xForWardedFor) {
return requestPostForm(url, requestParas, xForWardedFor,CHARACTER_ENCODING, CHARACTER_ENCODING);
}

/**
* 客户端登陆调用
* @param url                 请求url
* @param requestParas        请求参数
* @param xForWardedFor       请求ip(统计客户端登陆次数)
* @param requestCharacter    请求编码
* @param responseCharacter   响应编码
* @return
*/
public static String requestPostForm(String url, Map<String, String> requestParas,String xForWardedFor, String requestCharacter, String responseCharacter) {
HttpResponseWrapper httpResponseWrapper = null;
try {
httpResponseWrapper = requestPostFormResponse(url, requestParas, requestCharacter,xForWardedFor);
return httpResponseWrapper.getResponseString(responseCharacter);
} catch (Exception e) {
LOG.error(e);
} finally {
httpResponseWrapper.close();
}
return null;
}

/**
* POST方式提交表单数据,返回响应对象
* @param url                 请求url
* @param requestParas        请求参数
* @param xForWardedFor       请求ip(统计客户端登陆次数)
*/
public static HttpResponseWrapper requestPostFormResponse(String url, Map<String, String> requestParas, String requestCharacter,String xForWardedFor) throws ClientProtocolException, IOException {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient();
}else{
client =createHttpClient();
}
HttpPost httpPost = new HttpPost(url);
if(StringUtils.isNotEmpty(xForWardedFor)){
httpPost.addHeader("X-Forwarded-For", xForWardedFor);
}
List<NameValuePair> formParams = initNameValuePair(requestParas);
httpPost.setEntity(new UrlEncodedFormEntity(formParams, requestCharacter));
HttpResponse httpResponse = client.execute(httpPost); //执行POST请求
return new HttpResponseWrapper(client, httpResponse);
}

public static HttpClient createHttpClient(Map<String, Object> httpParams) {
HttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
if (params != null && httpParams != null) {
for(String key : httpParams.keySet()) {
params.setParameter(key, httpParams.get(key));
}
}
return httpClient;
}

public static HttpClient createHttpsClient(Map<String, Object> httpParams)  {
try {
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpParams params = httpClient.getParams();
if (params != null && httpParams != null) {
for(String key : httpParams.keySet()) {
params.setParameter(key, httpParams.get(key));
}
}
//TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
//使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);
//创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
return httpClient;
} catch (Exception e) {
LOG.error(e);
}
return null;
}

/**
*
* @autor: heyuxing  2014-11-14 下午8:02:50
* @param url 请求url
* @param params 请求参数
* @param httpParams 设置HttpClient.getParams()中的参数
* @return
* @return String
*/
public static String requestGet(String url, Map<String, Object> params, Map<String, Object> httpParams)  {
return requestGet(url, params, httpParams, null);
}

/**
*
* @param url 请求url
* @param params 请求参数
* @param httpParams 设置HttpClient.getParams()中的参数
* @param responseCharacter 处理应答response字符串使用的字符集
* @return
* @return String
*/
public static String requestGet(String url, Map<String, Object> params, Map<String, Object> httpParams, String responseCharacter)  {
StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("?").append(mapToUrl(params));

HttpResponseWrapper httpResponseWrapper = null;
try {
HttpClient client = null;
if (url.startsWith("https")) {
client =createHttpsClient(httpParams);
}else{
client =createHttpClient(httpParams);
}
HttpGet httpGet = new HttpGet(urlBuilder.toString());
HttpResponse httpResponse = client.execute(httpGet);

if(StringUtils.isEmpty(responseCharacter)) {
responseCharacter = CHARACTER_ENCODING;
}
return new HttpResponseWrapper(client, httpResponse).getResponseString(responseCharacter);
} catch (Exception e) {
LOG.error(e);
} finally {
if(httpResponseWrapper!=null){
httpResponseWrapper.close();
}
}
return null;
}
}


3、用到一个实体

package com.lvtu.error.process;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.util.Assert;

/**
*
* @ClassName: HttpParamEncodeEntity
* @Description: 请求参数编码
*
*/
public class HttpParamEncodeEntity extends StringEntity{

public HttpParamEncodeEntity(List<NameValuePair> formParams, String charset) {
super(ParamEncodeUtil.format(formParams,charset), ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}

private static class ParamEncodeUtil{

static String format(List<NameValuePair> formParams,String requestCharacter){
StringBuffer sb =new StringBuffer();
Assert.notEmpty(formParams);
for(NameValuePair nv:formParams){
if(sb.length()>0){
sb.append("&");
}
sb.append(encodeString(nv.getName(),requestCharacter));
sb.append("=");
sb.append(encodeString(nv.getValue(),requestCharacter));
}

return  sb.toString();
}

private static String encodeString(String str,String requestCharacter){
try {
return URLEncoder.encode(str, requestCharacter);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: