java 基础--httpclient 远程调用+DES/MD5加密

调用服务端代码地址

 加密MD5 BASE64 DES

package com.zhouwuji.test;

import java.io.IOException;  
import java.io.UnsupportedEncodingException;  
import java.security.MessageDigest;  
  

import javax.crypto.Cipher;  
import javax.crypto.spec.IvParameterSpec;  
import javax.crypto.spec.SecretKeySpec;  
  

import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  
  
/** 
 * 功能描述 
 * 加密常用类 
 */  
public class EncryptUtil {  
    // 密钥是16位长度的byte[]进行Base64转换后得到的字符串  
   // public static String key = "LmMGStGtOpF4xNyvYt54EQ==";  
   
    /** 
     * <li> 
     * 方法名称:encrypt</li> <li> 
     * 加密方法 
     * @param xmlStr 
     *            需要加密的消息字符串 
     * @return 加密后的字符串 
     */  
    public static String encrypt(String xmlStr,String key) {  
        byte[] encrypt = null;  
    
        try {  
            // 取需要加密内容的utf-8编码。  
            encrypt = xmlStr.getBytes("utf-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        // 取MD5Hash码,并组合加密数组  
        byte[] md5Hasn = null;  
        try {  
            md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        // 组合消息体  
        byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt);  
  
        // 取密钥和偏转向量  
        byte[] key1 = new byte[8];  
        byte[] iv = new byte[8];  
        getKeyIV(key, key1, iv);  
        SecretKeySpec deskey = new SecretKeySpec(key1, "DES");  
        IvParameterSpec ivParam = new IvParameterSpec(iv);  
  
        // 使用DES算法使用加密消息体  
        byte[] temp = null;  
        try {  
            temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        // 使用Base64加密后返回  
        return new BASE64Encoder().encode(temp);  
    }  
  
    /** 
     * <li> 
     * 方法名称:encrypt</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 解密方法 
     * </pre> 
     *  
     * </li> 
     *  
     * @param xmlStr 
     *            需要解密的消息字符串 
     * @return 解密后的字符串 
     * @throws Exception 
     */  
    public static String decrypt(String xmlStr,String key) throws Exception {  
        // base64解码  
        BASE64Decoder decoder = new BASE64Decoder();  
        byte[] encBuf = null;  
        try {  
            encBuf = decoder.decodeBuffer(xmlStr);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 取密钥和偏转向量  
        byte[] key1 = new byte[8];  
        byte[] iv = new byte[8];  
        getKeyIV(key, key1, iv);  
  
        SecretKeySpec deskey = new SecretKeySpec(key1, "DES");  
        IvParameterSpec ivParam = new IvParameterSpec(iv);  
  
        // 使用DES算法解密  
        byte[] temp = null;  
        try {  
            temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        // 进行解密后的md5Hash校验  
        byte[] md5Hash = null;  
        try {  
            md5Hash = EncryptUtil.MD5Hash(temp, 16, temp.length - 16);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        // 进行解密校检  
        for (int i = 0; i < md5Hash.length; i++) {  
            if (md5Hash[i] != temp[i]) {  
                // System.out.println(md5Hash[i] + "MD5校验错误。" + temp[i]);  
                throw new Exception("MD5校验错误。");  
            }  
        }  
  
        // 返回解密后的数组,其中前16位MD5Hash码要除去。  
        return new String(temp, 16, temp.length - 16, "utf-8");  
    }  
  
    /** 
     * <li> 
     * 方法名称:TripleDES_CBC_Encrypt</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 经过封装的三重DES/CBC加密算法,如果包含中文,请注意编码。 
     * </pre> 
     *  
     * </li> 
     *  
     * @param sourceBuf 
     *            需要加密内容的字节数组。 
     * @param deskey 
     *            KEY 由24位字节数组通过SecretKeySpec类转换而成。 
     * @param ivParam 
     *            IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。 
     * @return 加密后的字节数组 
     * @throws Exception 
     */  
    public static byte[] TripleDES_CBC_Encrypt(byte[] sourceBuf,  
            SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {  
        byte[] cipherByte;  
        // 使用DES对称加密算法的CBC模式加密  
        Cipher encrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");  
  
        encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);  
  
        cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);  
        // 返回加密后的字节数组  
        return cipherByte;  
    }  
  
    /** 
     * <li> 
     * 方法名称:TripleDES_CBC_Decrypt</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 经过封装的三重DES / CBC解密算法 
     * </pre> 
     *  
     * </li> 
     *  
     * @param sourceBuf 
     *            需要解密内容的字节数组 
     * @param deskey 
     *            KEY 由24位字节数组通过SecretKeySpec类转换而成。 
     * @param ivParam 
     *            IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。 
     * @return 解密后的字节数组 
     * @throws Exception 
     */  
    public static byte[] TripleDES_CBC_Decrypt(byte[] sourceBuf,  
            SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {  
  
        byte[] cipherByte;  
        // 获得Cipher实例,使用CBC模式。  
        Cipher decrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");  
        // 初始化加密实例,定义为解密功能,并传入密钥,偏转向量  
        decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);  
  
        cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);  
        // 返回解密后的字节数组  
        return cipherByte;  
    }  
  
    /** 
     * <li> 
     * 方法名称:DES_CBC_Encrypt</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 经过封装的DES/CBC加密算法,如果包含中文,请注意编码。 
     * </pre> 
     *  
     * </li> 
     *  
     * @param sourceBuf 
     *            需要加密内容的字节数组。 
     * @param deskey 
     *            KEY 由8位字节数组通过SecretKeySpec类转换而成。 
     * @param ivParam 
     *            IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。 
     * @return 加密后的字节数组 
     * @throws Exception 
     */  
    public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,  
            SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {  
        byte[] cipherByte;  
        // 使用DES对称加密算法的CBC模式加密  
        Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");  
  
        encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);  
  
        cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);  
        // 返回加密后的字节数组  
        return cipherByte;  
    }  
  
    /** 
     * <li> 
     * 方法名称:DES_CBC_Decrypt</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 经过封装的DES/CBC解密算法。 
     * </pre> 
     *  
     * </li> 
     *  
     * @param sourceBuf 
     *            需要解密内容的字节数组 
     * @param deskey 
     *            KEY 由8位字节数组通过SecretKeySpec类转换而成。 
     * @param ivParam 
     *            IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。 
     * @return 解密后的字节数组 
     * @throws Exception 
     */  
    public static byte[] DES_CBC_Decrypt(byte[] sourceBuf,  
            SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {  
  
        byte[] cipherByte;  
        // 获得Cipher实例,使用CBC模式。  
        Cipher decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");  
        // 初始化加密实例,定义为解密功能,并传入密钥,偏转向量  
        decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);  
  
        cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);  
        // 返回解密后的字节数组  
        return cipherByte;  
    }  
  
    /** 
     * <li> 
     * 方法名称:MD5Hash</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * MD5,进行了简单的封装,以适用于加,解密字符串的校验。 
     * </pre> 
     *  
     * </li> 
     *  
     * @param buf 
     *            需要MD5加密字节数组。 
     * @param offset 
     *            加密数据起始位置。 
     * @param length 
     *            需要加密的数组长度。 
     * @return 
     * @throws Exception 
     */  
    public static byte[] MD5Hash(byte[] buf, int offset, int length)  
            throws Exception {  
        MessageDigest md = MessageDigest.getInstance("MD5");  
        md.update(buf, offset, length);  
        return md.digest();  
    }  
  
    /** 
     * <li> 
     * 方法名称:byte2hex</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * 字节数组转换为二行制表示 
     * </pre> 
     *  
     * </li> 
     *  
     * @param inStr 
     *            需要转换字节数组。 
     * @return 字节数组的二进制表示。 
     */  
    public static String byte2hex(byte[] inStr) {  
        String stmp;  
        StringBuffer out = new StringBuffer(inStr.length * 2);  
  
        for (int n = 0; n < inStr.length; n++) {  
            // 字节做"与"运算,去除高位置字节 11111111  
            stmp = Integer.toHexString(inStr[n] & 0xFF);  
            if (stmp.length() == 1) {  
                // 如果是0至F的单位字符串,则添加0  
                out.append("0" + stmp);  
            } else {  
                out.append(stmp);  
            }  
        }  
        return out.toString();  
    }  
  
    /** 
     * <li> 
     * 方法名称:addMD5</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     * MD校验码 组合方法,前16位放MD5Hash码。 把MD5验证码byte[],加密内容byte[]组合的方法。 
     * </pre> 
     *  
     * </li> 
     *  
     * @param md5Byte 
     *            加密内容的MD5Hash字节数组。 
     * @param bodyByte 
     *            加密内容字节数组 
     * @return 组合后的字节数组,比加密内容长16个字节。 
     */  
    public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {  
        int length = bodyByte.length + md5Byte.length;  
        byte[] resutlByte = new byte[length];  
  
        // 前16位放MD5Hash码  
        for (int i = 0; i < length; i++) {  
            if (i < md5Byte.length) {  
                resutlByte[i] = md5Byte[i];  
            } else {  
                resutlByte[i] = bodyByte[i - md5Byte.length];  
            }  
        }  
  
        return resutlByte;  
    }  
  
    /** 
     * <li> 
     * 方法名称:getKeyIV</li> <li> 
     * 功能描述: 
     *  
     * <pre> 
     *  
     * </pre> 
     * </li> 
     *  
     * @param encryptKey 
     * @param key 
     * @param iv 
     */  
    public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {  
        // 密钥Base64解密  
        BASE64Decoder decoder = new BASE64Decoder();  
        byte[] buf = null;  
        try {  
            buf = decoder.decodeBuffer(encryptKey);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        // 前8位为key  
        int i;  
        for (i = 0; i < key.length; i++) {  
            key[i] = buf[i];  
        }  
        // 后8位为iv向量  
        for (i = 0; i < iv.length; i++) {  
            iv[i] = buf[i + 8];  
        }  
    }  
      
    public static void main(String[] args) throws Exception {  
        System.out.println(encrypt("欧长璐","LmMGStGtOpF4xNyvYt54EQ=="));  
        System.err.println(decrypt(null,"LmMGStGtOpF4xNyvYt54EQ=="));
    }  
} 
EncryptUtil
package com.zhouwuji.test;
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.HashMap;
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
  

import org.apache.http.HttpEntity;  
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.entity.ContentType;  
import org.apache.http.entity.mime.MultipartEntityBuilder;  
import org.apache.http.entity.mime.content.FileBody;  
import org.apache.http.entity.mime.content.StringBody;  
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;  
  
/** 
 * @web http://www.mobctrl.net 
 * @author Zheng Haibo 
 * @Description: 文件下载 POST GET 
 */  
public class HttpClientUtils {  
  
    /** 
     * 最大线程池 
     */  
    public static final int THREAD_POOL_SIZE = 5;  
  
    public interface HttpClientDownLoadProgress {  
        public void onProgress(int progress);  
    }  
  
    private static HttpClientUtils httpClientDownload;  
  
    private ExecutorService downloadExcutorService;  
  
    private HttpClientUtils() {  
        downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);  
    }  
  
    public static HttpClientUtils getInstance() {  
        if (httpClientDownload == null) {  
            httpClientDownload = new HttpClientUtils();  
        }  
        return httpClientDownload;  
    }  
  
    /** 
     * 下载文件 
     *  
     * @param url 
     * @param filePath 
     */  
    public void download(final String url, final String filePath) {  
        downloadExcutorService.execute(new Runnable() {  
  
            public void run() {  
                httpDownloadFile(url, filePath, null, null);  
            }  
        });  
    }  
  
    /** 
     * 下载文件 
     *  
     * @param url         请求地址
     * @param filePath    保存路径 
     * @param progress    进度回调 
     * @param headMap     传输参数
     */  
    public void download(final String url, final String filePath,  
            final HttpClientDownLoadProgress progress) {  
        downloadExcutorService.execute(new Runnable() {  
  
            public void run() {  
                 
                httpDownloadFile(url, filePath, progress, null);  
            }  
        });  
    }  
  
    /** 
     * 下载文件 
     *  
     * @param url 
     * @param filePath 
     */  
    private void httpDownloadFile(String url, String filePath,  
            HttpClientDownLoadProgress progress, Map<String, String> headMap) {  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpGet httpGet = new HttpGet(url);  
            setGetHead(httpGet, headMap);  
            CloseableHttpResponse response1 = httpclient.execute(httpGet);  
            try {  
                System.out.println(response1.getStatusLine());  
                HttpEntity httpEntity = response1.getEntity();  
                long contentLength = httpEntity.getContentLength();  
                InputStream is = httpEntity.getContent();  
                // 根据InputStream 下载文件  
                ByteArrayOutputStream output = new ByteArrayOutputStream();  
                byte[] buffer = new byte[4096];  
                int r = 0;  
                long totalRead = 0;  
                while ((r = is.read(buffer)) > 0) {  
                    output.write(buffer, 0, r);  
                    totalRead += r;  
                    if (progress != null) {// 回调进度  
                        progress.onProgress((int) (totalRead * 100 / contentLength));  
                    }  
                }  
                FileOutputStream fos = new FileOutputStream(filePath);  
                output.writeTo(fos);  
                output.flush();  
                output.close();  
                fos.close();  
                EntityUtils.consume(httpEntity);  
            } finally {  
                response1.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * get请求 
     *  
     * @param url 
     * @return 
     */  
    public String httpGet(String url) {  
        return httpGet(url, null);  
    }  
  
    /** 
     * http get请求 
     *  
     * @param url 
     * @return 
     */  
    public String httpGet(String url, Map<String, String> headMap) {  
        String responseContent = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpGet httpGet = new HttpGet(url);  
            CloseableHttpResponse response1 = httpclient.execute(httpGet);  
            setGetHead(httpGet, headMap);  
            try {  
                System.out.println(response1.getStatusLine());  
                HttpEntity entity = response1.getEntity();  
                responseContent = getRespString(entity);  
                System.out.println("debug:" + responseContent);  
                EntityUtils.consume(entity);  
            } finally {  
                response1.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
  
    public String httpPost(String url, Map<String, String> paramsMap) {  
        return httpPost(url, paramsMap, null);  
    }  
  
    /** 
     * http的post请求 
     *  
     * @param url 
     * @param paramsMap 
     * @return 
     */  
    public String httpPost(String url, Map<String, String> paramsMap,  
            Map<String, String> headMap) {  
        String responseContent = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpPost httpPost = new HttpPost(url);  
            setPostHead(httpPost, headMap);  
            setPostParams(httpPost, paramsMap);  
            CloseableHttpResponse response = httpclient.execute(httpPost);  
            try {  
                System.out.println(response.getStatusLine());  
                HttpEntity entity = response.getEntity();  
                responseContent = getRespString(entity);  
                EntityUtils.consume(entity);  
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        System.out.println("responseContent = " + responseContent);  
        return responseContent;  
    }  
  
    /** 
     * 设置POST的参数 
     *  
     * @param httpPost 
     * @param paramsMap 
     * @throws Exception 
     */  
    private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)  
            throws Exception {  
        if (paramsMap != null && paramsMap.size() > 0) {  
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
            Set<String> keySet = paramsMap.keySet();  
            for (String key : keySet) {  
                nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));  
            }  
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
        }  
    }  
  
    /** 
     * 设置http的HEAD 
     *  
     * @param httpPost 
     * @param headMap 
     */  
    private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {  
        if (headMap != null && headMap.size() > 0) {  
            Set<String> keySet = headMap.keySet();  
            for (String key : keySet) {  
                httpPost.addHeader(key, headMap.get(key));  
            }  
        }  
    }  
  
    /** 
     * 设置http的HEAD 
     *  
     * @param httpGet 
     * @param headMap 
     */  
    private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {  
        if (headMap != null && headMap.size() > 0) {  
            Set<String> keySet = headMap.keySet();  
            for (String key : keySet) {  
                httpGet.addHeader(key, headMap.get(key));  
            }  
        }  
    }  
  
    /** 
     * 上传文件 
     *  
     * @param serverUrl 
     *            服务器地址 
     * @param localFilePath 
     *            本地文件路径 
     * @param serverFieldName 
     * @param params 
     * @return 
     * @throws Exception 
     */  
    public String uploadFileImpl(String serverUrl, String localFilePath,  
            String serverFieldName, Map<String, String> params)  
            throws Exception {  
        String respStr = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpPost httppost = new HttpPost(serverUrl);  
            FileBody binFileBody = new FileBody(new File(localFilePath));  
  
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder  
                    .create();  
            // add the file params  
            multipartEntityBuilder.addPart(serverFieldName, binFileBody);  
            // 设置上传的其他参数  
            setUploadParams(multipartEntityBuilder, params);  
  
            HttpEntity reqEntity = multipartEntityBuilder.build();  
            httppost.setEntity(reqEntity);  
  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {  
                System.out.println(response.getStatusLine());  
                HttpEntity resEntity = response.getEntity();  
                respStr = getRespString(resEntity);  
                EntityUtils.consume(resEntity);  
            } finally {  
                response.close();  
            }  
        } finally {  
            httpclient.close();  
        }  
        System.out.println("resp=" + respStr);  
        return respStr;  
    }  
  
    /** 
     * 设置上传文件时所附带的其他参数 
     *  
     * @param multipartEntityBuilder 
     * @param params 
     */  
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,  
            Map<String, String> params) {  
        if (params != null && params.size() > 0) {  
            Set<String> keys = params.keySet();  
            for (String key : keys) {  
                multipartEntityBuilder  
                        .addPart(key, new StringBody(params.get(key),  
                                ContentType.TEXT_PLAIN));  
            }  
        }  
    }  
  
    /** 
     * 将返回结果转化为String 
     *  
     * @param entity 
     * @return 
     * @throws Exception 
     */  
    private String getRespString(HttpEntity entity) throws Exception {  
        if (entity == null) {  
            return null;  
        }  
        InputStream is = entity.getContent();  
        StringBuffer strBuf = new StringBuffer();  
        byte[] buffer = new byte[4096];  
        int r = 0;  
        while ((r = is.read(buffer)) > 0) {  
            strBuf.append(new String(buffer, 0, r, "UTF-8"));  
        }  
        return strBuf.toString();  
    }  
}  
HttpClientUtils
package com.zhouwuji.test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.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.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhouwuji.test.HttpClientUtils.HttpClientDownLoadProgress;
public class Test1 {
    
    public static void main(String[] args) throws Exception {  
        
            
      
        
        // POST 同步方法  
    
      /* Map<String, String> params = new HashMap<String, String>();  
       params.put("username",EncryptUtil.encrypt("admin", "LmMGStGtOpF4xNyvYt54EQ=="));  
       params.put("password",EncryptUtil.encrypt("123456", "LmMGStGtOpF4xNyvYt54EQ=="));  
       params.put("key", "LmMGStGtOpF4xNyvYt54EQ==");  
       String  body =HttpClientUtils.getInstance().httpPost("http://localhost:8080/project/json.do", params);  
       ObjectMapper mapper1 = new ObjectMapper();
       List<Use> beanList = mapper1.readValue(body, new TypeReference<List<Use>>() {});
       for (Use use : beanList) {
           use.setName(EncryptUtil.decrypt(use.getName(), "LmMGStGtOpF4xNyvYt54EQ=="));
            System.out.println(use);
        }*/
        
      /*HTTP/1.1 200 OK
     responseContent = [{"id":1,"name":"vHu9nk1qto0KjJE2bLqZDB7bmKezfapX","sex":"男"},{"id":2,"name":"sOisTida7RFXgb6jyBqt7sZfBdLwl1Uc","sex":"男"},{"id":3,"name":"cAZluNisTuWp5p7efVK2R9uUpvVpIfiE","sex":"女"}]
            Use [id=1, name=张三, sex=男]
            Use [id=2, name=李四, sex=男]
            Use [id=3, name=西施, sex=女]
          */
       
        // GET 同步方法  
        /*      String  body= HttpClientUtils.getInstance().httpGet(  
               "http://localhost:8080/project/json.do?username=abc");  
                 System.out.println(body);*/
      
        
        // 上传文件 POST 同步方法  
      try {  
           Map<String,String> uploadParams = new LinkedHashMap<String, String>();  
           uploadParams.put("username", "image");  
           uploadParams.put("userImageFileName", "testaa.png");  
           HttpClientUtils.getInstance().uploadFileImpl(  
                   "http://localhost:8080/project/upload.do", "D:/xp/test/sendLogDetail_201801.txt",  
                   "uploadfile", uploadParams);  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
 
         /** 
            * 测试下载文件 异步下载 
            */  
            
            HttpClientUtils.getInstance().download(  
                   "http://localhost:8080/project/download.do?filename=sendLogDetail_201801.txt", "D:\\xp\\test\\text.txt",  
                   new HttpClientDownLoadProgress() {  
                       public void onProgress(int progress) {  
                           System.out.println("download progress = " + progress);  
                       } 
                   });        
        
    }  
    
}
Test1
package com.zhouwuji.test;

public class Use {
        private int id;
        private String name;
        private String sex;
        public Use(int id, String name, String sex) {
            super();
            this.id = id;
            this.name = name;
            this.sex = sex;
        }
        public Use() {
            super();
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        @Override
        public String toString() {
            return "Use [id=" + id + ", name=" + name + ", sex=" + sex + "]";
        }
       
}
Use
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zhouwji.test</groupId>
    <artifactId>Sitfriend</artifactId>
    <parent>
        <groupId>com.zhouwuji.test</groupId>
        <artifactId>parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>
    <properties>
        <commons.httpcomponents.httpclient.version>4.5.5</commons.httpcomponents.httpclient.version>
        <commons.httpcomponents.httpclient.cache.version>4.5.5</commons.httpcomponents.httpclient.cache.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.zhouwuji.test</groupId>
            <artifactId>Sit</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>
         <!-- 远程调用httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${commons.httpcomponents.httpclient.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>${commons.httpcomponents.httpclient.cache.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.5</version>
        </dependency>
        
        <!--转换json https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>
</project>
pom.xml

 

posted @ 2018-01-25 18:01  周无极  阅读(1462)  评论(0编辑  收藏  举报