Java工具類之HttpClientTool

package com.taiping.facility.tool;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import com.taiping.common.Base64Tool;

public class HttpclientTool {
   
   public static Logger log = Logger.getLogger(HttpclientTool.class);

   public static String localIp = null;
   
   static{
      localIp = getLocalIp();
   }
   
   /**
    * get 方法
    * @param  url
    * @param params
    * @return
    */
   public static String get(String url, Object content, String encode) throws Exception {
      DataInputStream in = null;
      BufferedReader reader = null;
      String responseMsg = "";
      HttpClient httpclient = new HttpClient();
      GetMethod httpGet = new GetMethod(url);
      httpGet.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
      
      //(1)、這裏可以設置自己想要的編碼格式
      httpGet.getParams().setContentCharset("GB2312"); 
          
      //(3)、還可以如下這樣設置
      httpGet.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
           
      //(4)、當然同樣可以直接設置 httpClient 對象的編碼格式
      httpclient.getParams().setContentCharset("GB2312");
      
      //(5)、設置連接超時時間(單位毫秒)
      httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
      //(6)、設置讀數據超時時間(單位毫秒)      
      httpclient.getHttpConnectionManager().getParams().setSoTimeout(60000);
      try {
         // get
         int statusCode = httpclient.executeMethod(httpGet);
         System.out.println("statusCode:"+statusCode);
         
         // success
         if (statusCode == HttpStatus.SC_OK) {
            StringBuffer rspContent = new StringBuffer();
            in = new DataInputStream(httpGet.getResponseBodyAsStream());
            reader = new BufferedReader(new InputStreamReader(in, "gbk"));
            String aLine = "";
            while ((aLine = reader.readLine()) != null) {
               rspContent.append(aLine);
            }
            responseMsg = rspContent.toString();
            System.out.println("responseMsg:"+responseMsg);
         }
         // failure
         else {
            responseMsg = String.valueOf("statusCode:"+statusCode);
         }
      } catch (HttpException e) {
         throw new Exception(e.getMessage());
      } catch (IOException e) {
         throw new Exception(e.getMessage());
      } catch (Exception e) {
         throw new Exception(e.getMessage());
      } finally {
         httpGet.releaseConnection();
         if (reader != null) {
            reader.close();
         }
         if (in != null) {
            in.close();
         }
      }
   
      return responseMsg;
   }
   
   /**
    * post 方法
    * @param  url
    * @param params
    * @return
    */
   public static String post(String url, Object content, String encode) throws Exception {
      String responseMsg = "";
      byte[] responseBody = null;
      HttpClient httpclient = new HttpClient();
      PostMethod httpPost = new PostMethod(url);
      httpPost.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encode);
      httpPost.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset="+encode);
      // 設置連接超時時間(單位毫秒)
      httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(6000000);
      // 設置讀數據超時時間(單位毫秒)     
      httpclient.getHttpConnectionManager().getParams().setSoTimeout(6000000);
      try {
         httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
         // servlet
         if (content instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, String> map = (Map<String, String>)content;
            NameValuePair[] param = new NameValuePair[map.size()];
            
            int index = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {
               param[index] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), "GBK"));
             }
            
            httpPost.setRequestBody(param);
         }
         // rest
         else {
            httpPost.setRequestEntity(new StringRequestEntity((String)content,"plain/text", encode));
         }
         
         // post
         int statusCode = httpclient.executeMethod(httpPost);
         System.out.println("statusCode:"+statusCode);
         // success
         if (statusCode == HttpStatus.SC_OK) {
            responseBody = httpPost.getResponseBody();
         }
         // failure
         else {
            responseMsg = Base64Tool.encode(String.valueOf("statusCode:"+statusCode), encode);
         }
      } catch (HttpException e) {
         LogTool.error(HttpclientTool.class, e);
         throw new Exception(e.getMessage());
      } catch (IOException e) {
         LogTool.error(HttpclientTool.class, e);
         throw new Exception(e.getMessage());
      } catch (Exception e) {
         LogTool.error(HttpclientTool.class, e);
         throw new Exception(e.getMessage());
      } finally {
         httpPost.releaseConnection();
      }
   
      if (responseBody != null) {
         responseMsg = new String(responseBody, encode);
      }
      return responseMsg;
   }

   /**
    * 獲取本機IP地址
    * @return
    */
   public static String getLocalIp(){
      String localIp = "";
      Enumeration allNetInterfaces = null;
      try {
         allNetInterfaces = NetworkInterface.getNetworkInterfaces();
      } catch (SocketException e) {
         e.printStackTrace();
      }
      InetAddress ip = null;
      while (allNetInterfaces.hasMoreElements()) {
         NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//       System.out.println(netInterface.getName());
         Enumeration addresses = netInterface.getInetAddresses();
         while (addresses.hasMoreElements()) {
            ip = (InetAddress) addresses.nextElement();
            
            if (ip != null && ip instanceof Inet4Address) {

//             System.out.println("local IP address = " + ip.getHostAddress());
               localIp = ip.getHostAddress();
               if (!localIp.equals("127.0.0.1")) {
                  return localIp;
               }
               
            }
         }
      }
      return localIp;
   }
   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章