您的位置:首页 > 理论基础 > 计算机网络

HTTPClients的客户端执行请求,并获取响应,响应中解析具体的报文内容,最后返回请求内容将其转换成字符串

2019-06-07 15:21 691 查看

package com.fast.sky.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fast.sky.domain.UserEntity;

/**

  • JDK version:1.8

  • extends:

  • implements:

    *--------------------------------------------------------------

  • V1.0 创建 杨光 2019年6月7日
    *--------------------------------------------------------------

    */
    public class HttpRequestUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
    private static CloseableHttpResponse response = null;
    private static HttpEntity httpEntity = null;
    private static StringEntity entity = null;

    /**

    执行HTTP GET类型请求

  • @param requestURL/请求地址

  • @return 响应字符串
    */
    public synchronized static String httpGet(String requestURL)
    {
    try
    {

    if(null==requestURL || !requestURL.startsWith("http"))
    {
    logger.debug("The url is not exist ! Please check your Http request url .");
    }
    //1.创建请求类型:GET
    HttpGet get = new HttpGet(requestURL);
    //为请求类型的头部添加信息
    get.addHeader("Content-Type", "application/json;charset=utf-8");
    //2.利用HTTPClients的客户端执行请求,并获取响应
    response = HttpClients.custom().build().execute(get);
    int code = response.getStatusLine().getStatusCode();//获取执行之后的状态码,200执行正常
    if(200 != code)
    {
    throw new RuntimeException("HTTP GET Request Failed with Error code : " + code);
    }
    //3.从响应中解析具体的报文内容
    httpEntity = response.getEntity();
    //4.最后返回请求内容将其转换成字符串
    return EntityUtils.toString(httpEntity , "UTF-8");

    }
    catch (Exception e)
    {
    return “请求异常”;
    }
    }

/**

  • 执行HTTP POST类型请求

  • @param requestURL/请求地址

  • @param data/附带参数

  • @return 响应字符串
    */
    public synchronized static String httpPostRequest(String requestURL , String data)
    {
    try
    {
    if(null==requestURL || !requestURL.startsWith(“http”))
    {
    logger.error(“The url is not exist ! Please check your Http request url.”);
    }

    HttpPost post = new HttpPost(requestURL.trim());
    post.setHeader("Content-Type", "application/json;charset=utf-8");
    entity = new StringEntity(data , ContentType.APPLICATION_JSON );
    post.setEntity(entity);
    
    response = HttpClients.custom().build().execute(post);
    int code = response.getStatusLine().getStatusCode();
    if(200 != code) {
    throw new RuntimeException("HTTP POST Request Failed with Error code : " + code);
    }
    httpEntity = response.getEntity();
    return EntityUtils.toString(httpEntity , "UTF-8");

    }
    catch (Exception e)
    {
    return “请求异常”;
    }
    }

/**

  • 执行HTTP DELETE类型请求

  • @param requestURL/请求地址

  • @return 响应字符串
    */
    public synchronized static String httpDeleteRequest(String requestURL)
    {
    try
    {
    if(null == requestURL || !requestURL.startsWith(“http”))
    {
    logger.debug(“The url is not exist ! Please check your Http request url.”);
    }

    HttpDelete delete  = new HttpDelete(requestURL.trim());
    delete.addHeader("Content-Type", "application/json;charset=utf-8");
    
    response = HttpClients.custom().build().execute(delete);
    int code = response.getStatusLine().getStatusCode();
    if(200 != code)
    {
    throw new RuntimeException("HTTP DELETE Request Failed with Error code : " + code);
    }
    httpEntity = response.getEntity();
    return EntityUtils.toString(httpEntity , "UTF-8");

    }
    catch (Exception e)
    {
    return “请求异常”;
    }
    }

/**

  • 执行HTTP PUT类型请求

  • @param requestURL/请求地址

  • @param data/附带参数

  • @return 响应字符串
    */
    public synchronized static String httpPutRequest(String requestURL, String data)
    {
    try
    {
    if(null==requestURL || !requestURL.startsWith(“http”))
    {
    logger.debug(“The url is not exist ! Please check your Http request url.”);
    }

    HttpPut put = new HttpPut(requestURL.trim());
    put.setHeader("Content-Type", "application/json;charset=utf-8");
    entity = new StringEntity(data , ContentType.APPLICATION_JSON );
    put.setEntity(entity);
    
    response = HttpClients.custom().build().execute(put);
    int code = response.getStatusLine().getStatusCode();
    if(200 != code)
    {
    throw new RuntimeException("HTTP PUT Request Failed with Error code : " + code);
    }
    httpEntity = response.getEntity();
    return EntityUtils.toString(httpEntity , "UTF-8");

    }
    catch (Exception e)
    {
    return “请求异常”;
    }
    }

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: