码迷,mamicode.com
首页 > 其他好文 > 详细

两种访问接口的方式(get和post)

时间:2014-07-12 21:05:25      阅读:724      评论:0      收藏:0      [点我收藏+]

标签:杨凯   java   http   接口   

   跨机器、跨语言的远程访问形式一共有三种: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

两种访问接口的方式(get和post),布布扣,bubuko.com

两种访问接口的方式(get和post)

标签:杨凯   java   http   接口   

原文地址:http://blog.csdn.net/yangkai_hudong/article/details/37659909

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!