1. 程式人生 > >使用CloseableHttpClient 遠端呼叫介面

使用CloseableHttpClient 遠端呼叫介面

程式碼如下:

package com.ifeng.auto.api.support.httpclient;

import org.apache.commons.codec.Charsets;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Service("httpClientService")
public class HttpClientService {

    @Resource
   private CloseableHttpClient closeableHttpClient;

    @Resource
   private RequestConfig requestConfig;
   
   private Logger logger = Logger.getLogger(HttpClientService.class);
   
   /**
    * get請求
    * 
    * @param url 
    * @param params
    * @return
    */
   public String doGet(String url,Map<String,String> params) {
      HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        try {
           URIBuilder builder = new URIBuilder(url);
            if(null != params){
                for(Entry<String, String> entry : params.entrySet()){
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            httpGet = new HttpGet(builder.build());
            httpGet.setConfig(this.requestConfig);
           
            response = closeableHttpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
            }
        } catch (Exception e) {
           logger.error("HttpClientService doget Exception", e);
        } finally{
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("doget Exception info",e);
                }
            }
        }
        return "";
   }
   
   /**
    * post請求
    * 
    * @param url
    * @param params
    * @return
    */
   public String doPost(String url,Map<String,String> params) {
        CloseableHttpResponse response = null;
        try {
           HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(this.requestConfig);
            List<NameValuePair> nvps = new ArrayList<>();
            if(null != params){
                for(Entry<String,String> entry : params.entrySet()){
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, Charsets.UTF_8);
                httpPost.setEntity(entity);
            }
           
            response = closeableHttpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
            }
        } catch (Exception e) {
            logger.error("HttpClientService dopost Exception", e);
        } finally {
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("dopost Exception Info",e);
                }
            }
        }
        return "";
   }
}