java的HTTP工具類

來源:互聯網
上載者:User

標籤:params   max   tor   網路   status   bst   keyset   version   efault   

import java.io.IOException; 

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import flexjson.JSON;

/**
* HTTP工具類
*
* @author yaonian
*
*/
public class HttpUtils {

  private static Log log = LogFactory.getLog(HttpUtils.class);

/**
* 定義編碼格式 UTF-8
*/
  public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";

/**
* 定義編碼格式 GBK
*/
  public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";

  private static final String URL_PARAM_CONNECT_FLAG = "&";

  private static final String EMPTY = "";

  private static MultiThreadedHttpConnectionManager connectionManager = null;

  private static int connectionTimeOut = 25000;

  private static int socketTimeOut = 25000;

  private static int maxConnectionPerHost = 20;

  private static int maxTotalConnections = 20;

  private static HttpClient client;

static{
  connectionManager = new MultiThreadedHttpConnectionManager();
  connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
  connectionManager.getParams().setSoTimeout(socketTimeOut);
  connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
  connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
  client = new HttpClient(connectionManager);
}

/**
* POST方式提交資料
* @param url
* 待請求的URL
* @param params
* 要提交的資料
* @param enc
* 編碼
* @return
* 響應結果
* @throws IOException
* IO異常
*/
public static String URLPost(String url, Map<String, String> params, String enc){

  String response = EMPTY;
  PostMethod postMethod = null;
  try {
    postMethod = new PostMethod(url);
    postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
    //將表單的值放入postMethod中
    Set<String> keySet = params.keySet();
    for(String key : keySet){
      String value = params.get(key);
      postMethod.addParameter(key, value);
    }
    //執行postMethod
    int statusCode = client.executeMethod(postMethod);
    if(statusCode == HttpStatus.SC_OK) {
      response = postMethod.getResponseBodyAsString();
    }else{
      log.error("響應狀態代碼 = " + postMethod.getStatusCode());
    }
  }catch(HttpException e){
    log.error("發生致命的異常,可能是協議不對或者返回的內容有問題", e);
    e.printStackTrace();
  }catch(IOException e){
    log.error("發生網路異常", e);
    e.printStackTrace();
  }finally{
    if(postMethod != null){
      postMethod.releaseConnection();
      postMethod = null;
  }
  }

  return response;
  }

/**
* GET方式提交資料
* @param url
* 待請求的URL
* @param params
* 要提交的資料
* @param enc
* 編碼
* @return
* 響應結果
* @throws IOException
* IO異常
*/
public static String URLGet(String url, Map<String, String> params, String enc){

  String response = EMPTY;
  GetMethod getMethod = null;
  StringBuffer strtTotalURL = new StringBuffer(EMPTY);

  if(strtTotalURL.indexOf("?") == -1) {
    strtTotalURL.append(url).append("?").append(getUrl(params, enc));
  } else {
    strtTotalURL.append(url).append("&").append(getUrl(params, enc));
  }
  log.debug("GET請求URL = \n" + strtTotalURL.toString());

  try {
    getMethod = new GetMethod(strtTotalURL.toString());
    getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
    //執行getMethod
    int statusCode = client.executeMethod(getMethod);
    if(statusCode == HttpStatus.SC_OK) {
      response = getMethod.getResponseBodyAsString();
    }else{
      log.debug("響應狀態代碼 = " + getMethod.getStatusCode());
    }
  }catch(HttpException e){
    log.error("發生致命的異常,可能是協議不對或者返回的內容有問題", e);
    e.printStackTrace();
  }catch(IOException e){
    log.error("發生網路異常", e);
    e.printStackTrace();
  }finally{
    if(getMethod != null){
    getMethod.releaseConnection();
    getMethod = null;
  }
  }

  return response;
  }

/**
* 據Map產生URL字串
* @param map
* Map
* @param valueEnc
* URL編碼
* @return
* URL
*/
private static String getUrl(Map<String, String> map, String valueEnc) {

  if (null == map || map.keySet().size() == 0) {
    return (EMPTY);
  }
  StringBuffer url = new StringBuffer();
  Set<String> keys = map.keySet();
  for (Iterator<String> it = keys.iterator(); it.hasNext();) {
      String key = it.next();
      if (map.containsKey(key)) {
        String val = map.get(key);
        String str = val != null ? val : EMPTY;
      try {
        str = URLEncoder.encode(str, valueEnc);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);
    }
  }
  String strURL = EMPTY;
  strURL = url.toString();
  if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {
    strURL = strURL.substring(0, strURL.length() - 1);
  }

  return (strURL);
  }


public static void main(String[] args) {

  String url = "http://192.168.1.7:9909/";//項目路徑
  String charset = "utf-8"; //編碼格式
  String httpOrgCreateTest = url + "send"; //全路徑
  Map<String,String> createMap = new HashMap<String,String>(); //參數   索引值對

  //如
  createMap.put("shebeihao","01111");
  createMap.put("startTime","2017-12-14 14:25:00");
  createMap.put("endTime","2017-12-15 14:25:00");

  //GET方式調用
  String urlGet = URLGet(httpOrgCreateTest, createMap, charset);
  System.out.println("xxx"+urlGet);
}

/*

  Maven 匯入架包

  <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
  </dependency>

*/


}

java的HTTP工具類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.