http get请求

http get 请求方式

代码

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
/**
 * 
 * GET接口服务的JAVA示例
 * 
 */
public class HttpGetApiInvoker {
 
    private final static String URL = "http://test/url";
 
    private final static String REQUEST_CHARSET     =   "UTF-8";
    private final static String RESPONSE_CHARSET    =   "UTF-8";
    private final static int    CONNECT_TIMEOUT     =   5000;               //调用连接超时时间
    private final static int    REQUEST_TIMEOUT     =   10000;              //调用获取数据超时时间
 
    public static void main(String[] args) throws Exception{
    	HttpGetApiInvoker httpGetApiInvoker= new HttpGetApiInvoker();
        Map<String, Object> parameterList = httpGetApiInvoker.prepareParameter();
        String result = httpGetApiInvoker.invoke(parameterList);
        System.out.println(result);
    }
 
    /***
     * 准备业务参数
     * @return
     */
    private Map<String, Object> prepareParameter(){
        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("name", "xxx");
        parameterMap.put("password", "xxxxxxxx");
        return parameterMap;
    }
 
    /***
     * 拼接调用的URL
     * @param url
     * @param parametersMap 业务数据,作为参数
     * @return
     */
    private URI buildUri(String url, Map<String, Object> parametersMap) {
        if (null == parametersMap || parametersMap.isEmpty()) {
            return URI.create(url);
        }
        ArrayList list = new ArrayList(parametersMap.size());
        Iterator iterator = parametersMap.entrySet().iterator();
 
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            list.add(entry.getKey().toString().trim() + "=" + entry.getValue().toString().trim());
        }
        return list.isEmpty() ? URI.create(url) : URI.create(url + "?" + StringUtils.join(list, "&"));
    }
 
    /***
     * 没有使用长连接
     * @param parameterMap
     * @return  JSON格式的字符串
     * @throws IOException
     */
    private String invoke(Map<String, Object> parameterMap) throws IOException {
        HttpGet httpGet = null;
        String result = "";
        try {
 
            //拼接URL
            httpGet = new HttpGet(buildUri(URL,parameterMap));
 
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setSocketTimeout(REQUEST_TIMEOUT)
                    .build();
            httpGet.setConfig(requestConfig);
 
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + REQUEST_CHARSET);
 
            CloseableHttpClient httpClient = HttpClients.createDefault();
 
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
 
            //返回值不是200,进行错误处理
            if(HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()){
 
                //相关处理
                if(null != httpGet) {
                    httpGet.abort();
                }
                return result;
            }
 
            //获取结果
            result = EntityUtils.toString(httpEntity, RESPONSE_CHARSET);
 
        }catch(Exception e){
            if(null != httpGet){
                httpGet.abort();
            }
            throw e;
        }
        return result;
    }
}
项目依赖

<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-lang3</artifactId>
 <version>3.3.2 </version>
</dependency>

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version> 4.3.6</version>
</dependency>

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpcore</artifactId>
 <version>4.4</version>
</dependency>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值