java httpclient Tools

Meven 

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

- Code

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * HttpClient4.3工具类
 */
@Slf4j
public class HttpClientUtils {

    private static RequestConfig requestConfig = null;
    private static String charset = "utf-8";

    public static void main(String[] args) {
        JSONObject tt = new JSONObject();
        tt.put("aaa", "4444");

        Map mm = new HashMap();
        mm.put("aaa", "555");

        //System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", tt));
        // System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", mm));
        //System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", JSON.toJSONString(mm)));

        System.OUT .println ( " " + httpPostForm ( " http://127.0.0.1:8761/hi2 " , mm)); 
    } static {
         // setup request and transmission timeout 
        . requestConfig = RequestConfig.custom () setSocketTimeout ( 5000 ) .setConnectTimeout ( 5000 ) .build (); 
    } / * * 
     * @param URL 
     * @param obj 1. Map 3.JSONObject JSON string 2. 
     * @return the JSONObject * / public static the JSONObject HttpPost (URL string, Object obj) {
         // POST request return result 
        CloseableHttpClient httpClient =result:


    


    
     
      HttpClients.createDefault ();
        JsonResult the JSONObject = null ; 
        HttpPost HttpPost = new new HttpPost (URL);
         // set the timeout time and the transmission request 
        httpPost.setConfig (requestConfig);
         the try {
             IF ( null ! = Obj) { 
                StringEntity Entity = null ;
                 IF (obj the instanceof String) { 
                    Entity = new new StringEntity (obj.toString (), charset); 
                } the else  {
                    Entity = new new StringEntity(JSON.toJSONString(obj), charset);
                }
                entity.setContentEncoding(charset);
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            log.debug(" {} - {} ", url, obj);
            CloseableHttpResponse response = httpClient.execute(httpPost);

            return convertResponse(response);
        } catch (Exception e) {
            log.error("error HttpClientUtils {} - {} - {} " +URL, obj, E); 
        } the finally { 
            httpPost.releaseConnection (); 
        } 
        return JsonResult; 
    } 


    / * * 
     * POST request transmission String parameters such as: name = Jack & Sex =. 1 & type = 2 
     * the Content-type: file application / X-www- -urlencoded form 
     * 
     * @param URL address URL 
     * @param 
     * @return 
     * / 
    public  static the JSONObject httpPostForm (String URL, the Map <String, String> the params ) {
         // POST request return result 
        CloseableHttpClient httpClient = HttpClients.createDefault (); 
        JsonResult JSONObject =null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        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) {
            log.error("post请求提交失败:"+ URL, E); 
        } the finally HttpGet (URL);{ 
            HttpPost.releaseConnection (); 
        } 
        return JsonResult; 
    } 

    / * * 
     * get request to send 
     * 
     * @param URL path 
     * @return 
     * / 
    public  static the JSONObject HttpGet (String URL) {
         // get request return result 
        the JSONObject JsonResult = null ; 
        Client CloseableHttpClient = HttpClients.createDefault ();
         // send get request 
        HttpGet = request new new 
        request.setConfig (requestConfig); 
        the try {
            CloseableHttpResponse response = client.execute(request);

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

    private static JSONObject convertResponse(CloseableHttpResponse response) throws IOException, ParseException {
        // 请求发送成功,并得到响应
        if(. response.getStatusLine () getStatusCode () == HttpStatus.SC_OK) {
             // read json string returned by the server over the data 
            the HttpEntity Entity = response.getEntity (); 
            String strResult = EntityUtils.toString (Entity, " UTF- 8 " );
             // convert the string into json json objects 
            return JSONObject.parseObject (strResult); 
        } the else { 
            log.error ( " {} " , Response); 
        } 

        return  null ; 
    } 


}

 

Guess you like

Origin www.cnblogs.com/baobaoxiaokeai/p/11130947.html