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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM