HttpClient调用第三方系统详解

来源:互联网 发布:js输出99乘法表 编辑:程序博客网 时间:2024/05/21 08:56


一.使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接.


二.maven配置:
<dependency>  
   <groupId>com.fasterxml.jackson.core</groupId>  
   <artifactId>jackson-core</artifactId>  
   <version>2.5.2</version>  
</dependency>  

<dependency>
   <groupId>commons-collections</groupId>
   <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>   
<dependency>  
   <groupId>com.fasterxml.jackson.core</groupId>  
   <artifactId>jackson-databind</artifactId>  
   <version>2.5.2</version>  
</dependency>

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>

 

三,例子:








import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




public class HttpRequestUtil {
    public static final int STATUS_SUCCESS = 200;


    private static final int STATUS_FAILED = 500;


    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);


public static String doPost(String url, Map<String, String> params, int timeoutMillis) throws IOException {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String responseStr = "";
        try {
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMillis).setConnectTimeout(timeoutMillis).build();
            httppost.setConfig(requestConfig);


            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
           // String sVal = buildBizParam(params);
           // httppost.addHeader("Content-type","application/json; charset=utf-8"); 
           // httppost.setHeader("Accept", "application/json"); 
           // httppost.setEntity(new StringEntity(sVal, Charset.forName("UTF-8")));
            httppost.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                responseStr = EntityUtils.toString(response.getEntity());
                if (STATUS_SUCCESS != response.getStatusLine().getStatusCode()) {
                 
                }
            } finally {
                response.close();
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("error.", e);
            }
            return responseStr;
        }
    }




 public static String doPut(String url, Map<String, Object> params, int timeoutMillis) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String responseStr = "";
        Long start = System.currentTimeMillis();
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMillis).setConnectTimeout(timeoutMillis).build();
            HttpPut httput = new HttpPut(url);
            httput.setConfig(requestConfig);
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            httput.setEntity(entity);


            CloseableHttpResponse response = httpclient.execute(httput);
            try {
                int status = response.getStatusLine().getStatusCode();
                responseStr = EntityUtils.toString(response.getEntity());
                if (status != STATUS_SUCCESS) {
                  
                }
                return responseStr;
            } finally {
                response.close();
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("error.", e);
            }
        }
    }
}

0 0