HttpClient发送POST和GET请求

 1、使用HttpClient添加的maven依赖(尽量版本平齐或者比我的高,低的可能会出现找不到类的情况)

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

2、废话不多说,直接上代码 

/**
 * 作者:程序猿-南巷清风
 * 博客地址:https://blog.csdn.net/weixin_42152604(关注一下下^_^)
 * QQ:1821119445  java开发的朋友们可以加(非诚勿扰好吧!)
 */
public class UseHttpClient {
    /**
     *
     *get请求,参数拼接在地址上面
     * @param url 请求地址加参数
     * @return 响应
     *
     * 作者:程序猿-南巷清风
     * 博客地址:https://blog.csdn.net/weixin_42152604(关注一下下^_^)
     * QQ:1821119445  java开发的朋友们可以加(非诚勿扰好吧!)
     */
    public String getByUrl(String url){
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()         //如果没有必要的要求,可不设置
                .setConnectTimeout(5000)//设置连接超时时间
                .setConnectionRequestTimeout(5000)//设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//允许重定向
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    result = EntityUtils.toString(entity,"UTF-8");
                    EntityUtils.consume(entity);
                    System.out.println(result);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     *
     *get请求,参数放在map里
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     *
     * 作者:程序猿-南巷清风
     * 博客地址:https://blog.csdn.net/weixin_42152604(关注一下下^_^)
     * QQ:1821119445  java开发的朋友们可以加(非诚勿扰好吧!)
     */
    public String getByMap(String url, Map<String,String> map){
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> entry : map.entrySet())
        {
            pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        RequestConfig requestConfig = RequestConfig.custom()         //如果没有必要的要求,可不设置
                .setConnectTimeout(5000)//设置连接超时时间
                .setConnectionRequestTimeout(5000)//设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//允许重定向
                .build();
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpGet httpGet = new HttpGet(builder.build());
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    result = EntityUtils.toString(entity,"UTF-8");
                    EntityUtils.consume(entity);
                    System.out.println(result);
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
    /**
     *
     *post请求,参数放在map里
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     *
     * 作者:程序猿-南巷清风
     * 博客地址:https://blog.csdn.net/weixin_42152604(关注一下下^_^)
     * QQ:1821119445  java开发的朋友们可以加(非诚勿扰好吧!)
     */
    public String postByMap(String url, Map<String,String> map){
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> entry : map.entrySet())
        {
            pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        RequestConfig requestConfig = RequestConfig.custom()         //如果没有必要的要求,可不设置
                .setConnectTimeout(5000)//设置连接超时时间
                .setConnectionRequestTimeout(5000)//设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//允许重定向
                .build();
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));

            response = httpClient.execute(httpPost);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    result = EntityUtils.toString(entity,"UTF-8");
                    EntityUtils.consume(entity);
                    System.out.println(result);
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
    /**
     *
     *post请求,参数为json串
     * @param url 请求地址
     * @param jsonString 参数jsonString字符串
     * @return 响应
     *
     * 作者:程序猿-南巷清风
     * 博客地址:https://blog.csdn.net/weixin_42152604(关注一下下^_^)
     * QQ:1821119445  java开发的朋友们可以加(非诚勿扰好吧!)
     */
    public String postByMap(String url,String jsonString){
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;

        try {
            httpPost.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
            response = httpClient.execute(httpPost);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    result = EntityUtils.toString(entity,"UTF-8");
                    EntityUtils.consume(entity);
                    System.out.println(result);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值