兩種訪問介面的方式(get和post)

y_keven發表於2014-07-10

   跨機器、跨語言的遠端訪問形式一共有三種:scoket傳送資料包、http傳送請求、rmi遠端連線;

http傳送請求方式;分為post和get兩種方式

importjava.io.IOException;

importjava.io.InputStream;

import java.util.Map;

importjava.util.concurrent.atomic.AtomicInteger;

importorg.apache.commons.httpclient.HttpClient;

importorg.apache.commons.httpclient.HttpException;

importorg.apache.commons.httpclient.HttpStatus;

importorg.apache.commons.httpclient.MultiThreadedHttpConnectionManager;

importorg.apache.commons.httpclient.NameValuePair;

importorg.apache.commons.httpclient.methods.GetMethod;

importorg.apache.commons.httpclient.methods.PostMethod;

importorg.apache.commons.httpclient.params.HttpConnectionManagerParams;

importorg.apache.commons.io.IOUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

publicclass SendHttpUrl {

 

    privatefinalstatic Logger logger = LoggerFactory.getLogger(SendHttpUrl.class);

    privatestatic HttpClient httpClient = null;

    privatestaticMultiThreadedHttpConnectionManager connectionManager = null;// 多執行緒管理器

    privateintmaxThreadsTotal = 128;// 最大執行緒數

    privateintmaxThreadsPerHost = 32; // 分配給每個客戶端的最大執行緒數

    privateintconnectionTimeout = 15000;// 連線超時時間,毫秒

    privateintsoTimeout = 14000;// 讀取資料超時時間,毫秒

 

    publicvoid init() {

       connectionManager = newMultiThreadedHttpConnectionManager();

       HttpConnectionManagerParams params = newHttpConnectionManagerParams();

       params.setConnectionTimeout(connectionTimeout);

       params.setMaxTotalConnections(maxThreadsTotal);

       params.setSoTimeout(soTimeout);

       if (maxThreadsTotal > maxThreadsPerHost) {

           params.setDefaultMaxConnectionsPerHost(maxThreadsPerHost);

       } else {

           params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);

       }

       connectionManager.setParams(params);

       httpClient = new HttpClient(connectionManager);

       httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

       httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    }

 

    /**

    * get方式訪問

    *

    * @param url

    * @param callType

    * @param parmMap

    * @return

    */

    private String callByGet(Stringurl, String callType, Map<String, String> parmMap) {

       if (logger.isDebugEnabled()){

           logger.debug("in get,url:" + url);

       }

       GetMethod getMethod = new GetMethod(url);

       int statusCode = 0;

       try {

           statusCode = httpClient.executeMethod(getMethod);

           if (logger.isDebugEnabled()){

                logger.debug("inget,statusCode:" + statusCode);

           }

           if (statusCode != HttpStatus.SC_OK) {

                // 訪問失敗

                logger.error("in get,訪問appagent失敗。網路問題。statusCode:" + statusCode);

                returnnull;

           }

           InputStream inputStream = getMethod.getResponseBodyAsStream();

           if (inputStream == null) {

               // 訪問正常:獲取到的資料為空

                logger.error("in get,從appagent返回的資料為空!");

                returnnull;

           }

           String rtn = IOUtils.toString(inputStream, "utf-8");

           return rtn;

       } catch (HttpException e) {

           logger.error("get方式訪問appagent失敗!", e);

           returnnull;

       } catch (IOException e) {

           logger.error("get方式訪問appagent失敗!", e);

           returnnull;

       } finally {

           getMethod.releaseConnection();

       }

    }

 

    /**

    * post方式訪問

    *

    * @param url

    * @param callType

    * @param parmMap

    * @return

    */

    private String callByPost(Stringurl, String callType, Map<String, String> parmMap) {

       if (logger.isDebugEnabled()){

            logger.debug("inpost,url:" + url);

       }

       PostMethod p = new PostMethod(url);

       if (parmMap != null) {

           NameValuePair[] params = newNameValuePair[parmMap.size()];

           AtomicInteger atomicInteger = new AtomicInteger(0);

           for (Map.Entry<String, String> parm :parmMap.entrySet()) {

                NameValuePair parmValue = newNameValuePair(parm.getKey(), parm.getValue());

               params[atomicInteger.getAndIncrement()] = parmValue;

           }

 

            p.setRequestBody(params);

       }

       try {

           int statusCode = httpClient.executeMethod(p);

           logger.debug("inget,statusCode:" + statusCode);

           if (statusCode != HttpStatus.SC_OK) {

                // 異常

                logger.error("in post,訪問appagent失敗。網路問題。statusCode:" + statusCode);

                returnnull;

           }

           InputStream inputStream = p.getResponseBodyAsStream();

           if (inputStream == null) {

                // 訪問正常

                logger.error("in post,從appagent返回的資料為空!");

                returnnull;

           }

           String rtn = IOUtils.toString(inputStream, "utf-8");

           return rtn;

       } catch (HttpException e) {

           logger.error("post方式訪問appagent失敗!", e);

           returnnull;

       } catch (IOException e) {

           logger.error("post方式訪問appagent失敗!", e);

           returnnull;

       } finally {

           p.releaseConnection();

       }

    }

}



轉正請指明:blog.csdn.net/yangkai_hudong

相關文章