简单的客户端HttpClient请求实现类

1 篇文章 0 订阅
1 篇文章 0 订阅

    前几天,一直用的前辈写好的客户端请求实现类,突然之间有一个请求,不好用了。然后,发现其中的一些错误。可能是现在用的方法需求更多了!所以,突然就想自己写一个客户端请求的轮子,首先从简单写一个客户端请求实现类开始吧。

实现类:

因为,平时用的大都是get,post请求,所以今天只写一个get,post请求的json方法吧,默认为TFS-8编码

package com.jsalpha.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author dengjingsi
 * 发送请求客户端
 */
public class HttpClientRequest {
    /**
     * 把参数组装到url地址中
     * @param url
     * @param param
     * @return
     */
    private String getUrl(String url,Map<String,String> param) throws UnsupportedEncodingException {
        return url+getStringParam(param);
    }

    /**
     * 把param键值对,拼接成url参数形式
     * @param param
     * @return
     * @throws UnsupportedEncodingException
     */
    private String getStringParam(Map<String,String> param) throws UnsupportedEncodingException {
        if(null != param && param.size()>0){
            StringBuilder stringUrl = new StringBuilder("?");
            for(Map.Entry<String,String> entry : param.entrySet()){
                stringUrl.append(URLEncoder.encode(entry.getKey(),"UTF-8")).append('=').append(URLEncoder.encode(entry.getValue(),"UTF-8")).append('&');
            }
            return stringUrl.toString().substring(0,stringUrl.length()-1);
        }
        return "";
    }

//    /**
//     * get请求
//     * @param httpGet
//     * @return
//     * @throws IOException
//     */
//    public String get(HttpGet httpGet) throws IOException {
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        String data;
//        response = httpclient.execute(httpGet);
//        HttpEntity httpEntity = response.getEntity();
//        data = EntityUtils.toString(httpEntity,"UTF-8");
//        EntityUtils.consume(httpEntity);
//        response.close();
//        return data;
//    }
//
//    /**
//     * post请求
//     * @param httpPost
//     * @param body
//     * @return
//     * @throws IOException
//     */
//    public String post(HttpPost httpPost,String body) throws IOException {
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        if(null != body){
//            HttpEntity stringEntity = new StringEntity(body,"UTF-8");
//            httpPost.setEntity(stringEntity);
//        }
//        CloseableHttpResponse response = null;
//        String data;
//        response = httpClient.execute(httpPost);
//        HttpEntity httpEntity = response.getEntity();
//        data = EntityUtils.toString(httpEntity,"UTF-8");
//        EntityUtils.consume(httpEntity);
//        response.close();
//        return data;
//    }
//
//    /**
//     * put请求
//     * @param httpPut
//     * @param body
//     * @return
//     * @throws IOException
//     */
//    public String put(HttpPut httpPut, String body) throws IOException {
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        if (null != body){
//            HttpEntity stringEntity = new StringEntity(body,"UTF-8");
//            httpPut.setEntity(stringEntity);
//        }
//        CloseableHttpResponse response = null;
//        String data;
//        response = httpClient.execute(httpPut);
//        HttpEntity httpEntity = response.getEntity();
//        data = EntityUtils.toString(httpEntity,"UTF-8");
//        EntityUtils.consume(httpEntity);
//        response.close();
//        return data;
//    }

    /**
     * 根据方法参数创建request请求
     * @param url
     * @param method
     * @param param
     * @return
     * @throws UnsupportedEncodingException
     */
    private HttpUriRequest getRequest(String url, String method, Map<String,String> param) throws UnsupportedEncodingException {
        url = getUrl(url,param);
        if("POST".equalsIgnoreCase(method)){
            return new HttpPost(url);
        }else if("GET".equalsIgnoreCase(method)){
            return new HttpGet(url);
        }else{
            return new HttpPut(url);
        }
    }
    /**
     * 发送客户端请求方法
     * @param url
     * @param param
     * @param method
     * @param body
     * @return
     * @throws IOException
     */
    private String request(String url, Map<String,String> param, String method, String body, String contentType) throws IOException {
        url = getUrl(url,param);
        HttpUriRequest httpUriRequest = getRequest(url,method,param);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        if (contentType != null) {
            httpUriRequest.addHeader("Content-Type", contentType);
        }
        if (null != body){
            HttpEntity stringEntity = new StringEntity(body,"UTF-8");
            ((HttpEntityEnclosingRequestBase)httpUriRequest).setEntity(stringEntity);
        }
        CloseableHttpResponse response = null;
        String data;
        response = httpClient.execute(httpUriRequest);
        HttpEntity httpEntity = response.getEntity();
        data = EntityUtils.toString(httpEntity,"UTF-8");
        EntityUtils.consume(httpEntity);
        response.close();
        return data;
    }

    /**
     * post的json请求
     * @param url
     * @param param
     * @param body
     * @return
     * @throws IOException
     */
    public String postJson(String url,Map<String,String> param,String body) throws IOException {
        return request(url,param,"POST",body,"application/json");
    }

    /**
     * get请求
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public String get(String url,Map<String,String> param) throws IOException {
        return request(url,param,"GET",null,"application/json");
    }
}

测试类:

package com.jsalpha.utils;

import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;

public class TestHttpClientRequest {
    @Test
    public void test(){
        String data;
        HttpClientRequest httpClientRequest = new HttpClientRequest();
        try {
            data = httpClientRequest.get("http://172.16.1.5:8085/calcPentyValueItems?taskId=3127459475161088",new HashMap<>());
            System.out.println(data);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("2");
        }finally {
            System.out.println("3");
        }
    }
    @Test
    public void testPost(){
        String data;
        HttpClientRequest httpClientRequest = new HttpClientRequest();
        try {
            data = httpClientRequest.postJson("http://localhost:8187/examination/student/execute",null,"");
            System.out.println(data);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("2");
        }finally {
            System.out.println("3");
        }
    }
}

注意:测试类里边是我自己项目里边的请求地址,小伙伴要验证,请输入自己的请求地址。切记不要输入类似百度地址(www.baidu.com),我实现的只是客户端发送服务器请求而已,百度类似的地址是需要浏览器发送的,服务器会去解析请求头,看你的发送端是什么浏览器等信息。我这里没有实现请求头等一些信息,可能会报错。哈哈哈,还需小伙伴多多指点。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值