HttpClientUtil 等各类工具类的编写

来源:互联网 发布:辐射4n卡优化补丁 编辑:程序博客网 时间:2024/06/05 11:30
package com.taotao.common.utils;import java.io.IOException;import java.net.URI;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.NameValuePair;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.client.utils.URIBuilder;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class HttpClientUtil {public static String doGet(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse response = null;try {// 创建uriURIBuilder builder = new URIBuilder(url);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求HttpGet httpGet = new HttpGet(uri);// 执行请求response = httpclient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {resultString = EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpclient.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}public static String doGet(String url) {return doGet(url, null);}public static String doPost(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建参数列表if (param != null) {List<NameValuePair> paramList = new ArrayList<>();for (String key : param.keySet()) {paramList.add(new BasicNameValuePair(key, param.get(key)));}// 模拟表单UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);httpPost.setEntity(entity);}// 执行http请求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "utf-8");} catch (Exception e) {e.printStackTrace();} finally {try {response.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return resultString;}public static String doPost(String url) {return doPost(url, null);}public static String doPostJson(String url, String json) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建请求内容StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);httpPost.setEntity(entity);// 执行http请求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "utf-8");} catch (Exception e) {e.printStackTrace();} finally {try {response.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return resultString;}}
package com.taotao.common.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;/** * ftp上传下载工具类 * <p>Title: FtpUtil</p> * <p>Description: </p> * <p>Company: www.itcast.com</p>  * @author入云龙 * @date2015年7月29日下午8:11:51 * @version 1.0 */public class FtpUtil {/**  * Description: 向FTP服务器上传文件  * @param host FTP服务器hostname  * @param port FTP服务器端口  * @param username FTP登录账号  * @param password FTP登录密码  * @param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名  * @param input 输入流  * @return 成功返回true,否则返回false  */  public static boolean uploadFile(String host, int port, String username, String password, String basePath,String filePath, String filename, InputStream input) {boolean result = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(host, port);// 连接FTP服务器// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器ftp.login(username, password);// 登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return result;}//切换到上传目录if (!ftp.changeWorkingDirectory(basePath+filePath)) {//如果目录不存在创建目录String[] dirs = filePath.split("/");String tempPath = basePath;for (String dir : dirs) {if (null == dir || "".equals(dir)) continue;tempPath += "/" + dir;if (!ftp.changeWorkingDirectory(tempPath)) {if (!ftp.makeDirectory(tempPath)) {return result;} else {ftp.changeWorkingDirectory(tempPath);}}}}//设置上传文件的类型为二进制类型ftp.setFileType(FTP.BINARY_FILE_TYPE);//上传文件if (!ftp.storeFile(filename, input)) {return result;}input.close();ftp.logout();result = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return result;}/**  * Description: 从FTP服务器下载文件  * @param host FTP服务器hostname  * @param port FTP服务器端口  * @param username FTP登录账号  * @param password FTP登录密码  * @param remotePath FTP服务器上的相对路径  * @param fileName 要下载的文件名  * @param localPath 下载后保存到本地的路径  * @return  */  public static boolean downloadFile(String host, int port, String username, String password, String remotePath,String fileName, String localPath) {boolean result = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(host, port);// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器ftp.login(username, password);// 登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return result;}ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录FTPFile[] fs = ftp.listFiles();for (FTPFile ff : fs) {if (ff.getName().equals(fileName)) {File localFile = new File(localPath + "/" + ff.getName());OutputStream is = new FileOutputStream(localFile);ftp.retrieveFile(ff.getName(), is);is.close();}}ftp.logout();result = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return result;}public static void main(String[] args) {try {          FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));          boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);          System.out.println(flag);      } catch (FileNotFoundException e) {          e.printStackTrace();      }  }}
package com.taotao.common.utils;import java.io.PrintWriter;import java.io.StringWriter;public class ExceptionUtil {/** * 获取异常的堆栈信息 * @param t * @return */public static String getStackTrace(Throwable t) {StringWriter sw = new StringWriter();PrintWriter pw = new PrintWriter(sw);try {t.printStackTrace(pw);return sw.toString();} finally {pw.close();}}}
package com.taotao.common.utils;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** *  * Cookie 工具类 * */public final class CookieUtils {    /**     * 得到Cookie的值, 不编码     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName) {        return getCookieValue(request, cookieName, false);    }    /**     * 得到Cookie的值,     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {        Cookie[] cookieList = request.getCookies();        if (cookieList == null || cookieName == null) {            return null;        }        String retValue = null;        try {            for (int i = 0; i < cookieList.length; i++) {                if (cookieList[i].getName().equals(cookieName)) {                    if (isDecoder) {                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");                    } else {                        retValue = cookieList[i].getValue();                    }                    break;                }            }        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return retValue;    }    /**     * 得到Cookie的值,     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {        Cookie[] cookieList = request.getCookies();        if (cookieList == null || cookieName == null) {            return null;        }        String retValue = null;        try {            for (int i = 0; i < cookieList.length; i++) {                if (cookieList[i].getName().equals(cookieName)) {                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);                    break;                }            }        } catch (UnsupportedEncodingException e) {         e.printStackTrace();        }        return retValue;    }    /**     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue) {        setCookie(request, response, cookieName, cookieValue, -1);    }    /**     * 设置Cookie的值 在指定时间内生效,但不编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage) {        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);    }    /**     * 设置Cookie的值 不设置生效时间,但编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, boolean isEncode) {        setCookie(request, response, cookieName, cookieValue, -1, isEncode);    }    /**     * 设置Cookie的值 在指定时间内生效, 编码参数     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage, boolean isEncode) {        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);    }    /**     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage, String encodeString) {        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);    }    /**     * 删除Cookie带cookie域名     */    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,            String cookieName) {        doSetCookie(request, response, cookieName, "", -1, false);    }    /**     * 设置Cookie的值,并使其在指定时间内生效     *      * @param cookieMaxage cookie生效的最大秒数     */    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,            String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {        try {            if (cookieValue == null) {                cookieValue = "";            } else if (isEncode) {                cookieValue = URLEncoder.encode(cookieValue, "utf-8");            }            Cookie cookie = new Cookie(cookieName, cookieValue);            if (cookieMaxage > 0)                cookie.setMaxAge(cookieMaxage);            if (null != request) {// 设置域名的cookie            String domainName = getDomainName(request);            System.out.println(domainName);                if (!"localhost".equals(domainName)) {                cookie.setDomain(domainName);                }            }            cookie.setPath("/");            response.addCookie(cookie);        } catch (Exception e) {         e.printStackTrace();        }    }    /**     * 设置Cookie的值,并使其在指定时间内生效     *      * @param cookieMaxage cookie生效的最大秒数     */    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,            String cookieName, String cookieValue, int cookieMaxage, String encodeString) {        try {            if (cookieValue == null) {                cookieValue = "";            } else {                cookieValue = URLEncoder.encode(cookieValue, encodeString);            }            Cookie cookie = new Cookie(cookieName, cookieValue);            if (cookieMaxage > 0)                cookie.setMaxAge(cookieMaxage);            if (null != request) {// 设置域名的cookie            String domainName = getDomainName(request);            System.out.println(domainName);                if (!"localhost".equals(domainName)) {                cookie.setDomain(domainName);                }            }            cookie.setPath("/");            response.addCookie(cookie);        } catch (Exception e) {         e.printStackTrace();        }    }    /**     * 得到cookie的域名     */    private static final String getDomainName(HttpServletRequest request) {        String domainName = null;        String serverName = request.getRequestURL().toString();        if (serverName == null || serverName.equals("")) {            domainName = "";        } else {            serverName = serverName.toLowerCase();            serverName = serverName.substring(7);            final int end = serverName.indexOf("/");            serverName = serverName.substring(0, end);            final String[] domains = serverName.split("\\.");            int len = domains.length;            if (len > 3) {                // www.xxx.com.cn                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];            } else if (len <= 3 && len > 1) {                // xxx.com or xxx.cn                domainName = "." + domains[len - 2] + "." + domains[len - 1];            } else {                domainName = serverName;            }        }        if (domainName != null && domainName.indexOf(":") > 0) {            String[] ary = domainName.split("\\:");            domainName = ary[0];        }        return domainName;    }}
//web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="taotao" version="2.5"><display-name>taotao-manager</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 加载spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 解决post乱码 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- springmvc的前端控制器 --><servlet><servlet-name>taotao-manager</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>taotao-manager</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>