HttpClient操作示例

package tpzc.work.ipa.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * date: 2020/6/1 14:17
 *
 * @author xn_liutao
 * @since JDK 1.8
 */
public class HttpClientUtils {

    private static final Logger LOGGER = LogManager.getLogger(HttpClientUtils.class);

    private static String charset = "utf-8";

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClientConfig.getHttpClient();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        try {
            CloseableHttpResponse response = client.execute(request);

            jsonResult = convertResponse(response);
        } catch (Exception e) {
            LOGGER.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如:name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url url地址
     * @param
     * @return
     */
    public static JSONObject httpPost(String url, Map<String, String> params) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClientConfig.getHttpClient();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        try {
            if (null != params) {
                //组织请求参数
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                if (params != null && params.size() > 0) {
                    Set<String> keySet = params.keySet();
                    for (String key : keySet) {
                        paramList.add(new BasicNameValuePair(key, params.get(key)));
                    }
                }

                httpPost.setEntity(new UrlEncodedFormEntity(paramList, charset));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return convertResponse(response);
        } catch (IOException e) {
            LOGGER.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }


    private static JSONObject convertResponse(CloseableHttpResponse response) throws IOException, ParseException {
        // 请求发送成功,并得到响应
        JSONObject jsonObject = new JSONObject();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 读取服务器返回过来的json字符串数据
            HttpEntity entity = response.getEntity();
            String strResult = EntityUtils.toString(entity, "utf-8");
            // 把json字符串转换成json对象
            jsonObject = JSON.parseObject(strResult);
        }
        jsonObject.put("status",response.getStatusLine().getStatusCode());
        return jsonObject;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值