1. 程式人生 > >java使用httpclient封裝post請求

java使用httpclient封裝post請求

我們程式設計師在專案開發過程中,經常用到介面,目前比較流行httpclient  技術。以下是我之前封裝的httpclient的post請求 ,希望對大家有所幫助:

精簡程式碼如下:可以直接複製使用

 public static String postTDH(String url, String body, String mimeType,
            String charset, Integer connTimeout, Integer readTimeout) throws IOException, GeneralSecurityException  
    {  
        String result = "";
        HttpClient client = null;
        HttpPost post = new HttpPost(url);  
        try {  
            /*HttpEntity entity = new StringEntity(body, ContentType.create(  
                    mimeType, charset));  
            post.setEntity(entity);*/  
            StringEntity s = new StringEntity(body.toString(),
                    Charset.forName("utf-8"));
            s.setContentEncoding("UTF-8");
            post.setEntity(s);
            // 設定引數  
            Builder customReqConf = RequestConfig.custom();  
            if (connTimeout != null) {  
                customReqConf.setConnectTimeout(connTimeout);  
            }  
            if (readTimeout != null) {  
                customReqConf.setSocketTimeout(readTimeout);  
            }  
            post.setConfig(customReqConf.build());
            HttpResponse res;  
            if (url.startsWith("https")) {  
                // 執行 Https 請求.  
                client = createSSLInsecureClient();  
                res = client.execute(post);  
            } else {  
                // 執行 Http 請求.  
                client = HttpClientUtils.client;
                res = client.execute(post);
            }  
            int statusCode = res.getStatusLine().getStatusCode();
            System.out.println("返回碼:"+statusCode);
            //result = IOUtils.toString(res.getEntity().getContent(), charset);  
            
            result = UnicodeToZ.decodeUnicode(EntityUtils
                    .toString(res.getEntity()));
            logger.info("################傳送報文內容:################");
            logger.info(body);
            logger.info("################返回報文內容:################");
            logger.info(result);
        }finally {  
            post.releaseConnection();  
            if (url.startsWith("https") && client != null  
                    && client instanceof CloseableHttpClient) {  
                ((CloseableHttpClient) client).close();  
            }  
        }  
        return result;
        
    }  
Integer connTimeout, Integer readTimeout;介面超時時間設定
UnicodeToZ.decodeUnicode(EntityUtils .toString(res.getEntity()));返回的報文進行中文裝換(選擇性使用)
public class UnicodeToZ {
    public static String decodeUnicode(String theString) {    

        char aChar;    
       int len = theString.length();    
       StringBuffer outBuffer = new StringBuffer(len);    
       for (int x = 0; x < len;) {    
           aChar = theString.charAt(x++);    
           if (aChar == '\\') {    
               aChar = theString.charAt(x++);    
               if (aChar == 'u') {    
                   // Read the xxxx    
                   int value = 0;    
                   for (int i = 0; i < 4; i++) {    
                       aChar = theString.charAt(x++);    
                       switch (aChar) {    
                       case '0':    
                       case '1':    
                       case '2':    
                       case '3':    
                       case '4':    
                       case '5':    
                       case '6':    
                       case '7':    
                       case '8':    
                       case '9':    
                           value = (value << 4) + aChar - '0';    
                           break;    
                       case 'a':    
                       case 'b':    
                       case 'c':    
                       case 'd':    
                       case 'e':    
                       case 'f':    
                           value = (value << 4) + 10 + aChar - 'a';    
                           break;    
                       case 'A':    
                       case 'B':    
                       case 'C':    
                       case 'D':    
                       case 'E':    
                       case 'F':    
                           value = (value << 4) + 10 + aChar - 'A';    
                           break;    
                       default:    
                           throw new IllegalArgumentException(    
                                   "Malformed   \\uxxxx   encoding.");    
                       }    
                   }    
                   outBuffer.append((char) value);    
               } else {    
                   if (aChar == 't')    
                       aChar = '\t';    
                   else if (aChar == 'r')    
                       aChar = '\r';    
                   else if (aChar == 'n')    
                       aChar = '\n';    
                   else if (aChar == 'f')    
                       aChar = '\f';    
                   outBuffer.append(aChar);    
               }    
           } else    
               outBuffer.append(aChar);    
       }    
       return outBuffer.toString();    
   }  
}


改轉換方法  大家可以詳細研究。有不明白的地方大家可以留言,博主會及時幫你解決。